-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider_smoke_commands.py
More file actions
6477 lines (5978 loc) · 236 KB
/
provider_smoke_commands.py
File metadata and controls
6477 lines (5978 loc) · 236 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CLI command for opt-in provider smoke checks."""
from __future__ import annotations
import asyncio
import json
import logging
import os
import sys
import tempfile
from collections.abc import Callable, Mapping
from dataclasses import asdict, dataclass, field, replace
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from agents.runtime import (
RuntimeRequirements,
create_runtime_session,
get_runtime_mode,
normalize_runtime_mode,
resume_runtime_session,
run_runtime_session,
)
from agents.runtime.adapters.completion import CompletionRuntimeSession
from agents.runtime.adapters.generic_edit import inspect_generic_edit_resume_artifacts
from agents.runtime.fallback import capabilities_for_runtime_mode
from cli.autonomous_readiness_text import format_autonomous_readiness_requirements
from core.autonomy_level import MUTATING_SUBAGENTS_ENV
from core.autonomy_policy import (
DEFAULT_MAX_HISTORY_AGE_DAYS,
DEFAULT_MIN_STABLE_RUNS,
DEFAULT_REQUIRED_E2E_RUNS,
DEFAULT_REQUIRED_LIVE_FAULT_CASES,
DEFAULT_REQUIRED_LIVE_TASK_FAMILIES,
DIRECT_API_PROVIDERS,
AutonomyPolicy,
autonomy_policy_for,
)
from core.paths import (
AUTO_CODE_RUNTIME_DIR,
PROVIDER_SMOKE_HISTORY_FILENAME,
provider_smoke_history_path,
resolve_provider_smoke_history_path,
)
from core.providers.base import (
ProviderToolCall,
ProviderToolCallResponse,
SessionConfig,
)
from core.providers.config import ProviderConfig
from core.providers.cost_calculator import (
MODEL_PRICING,
calculate_cost,
format_cost,
get_model_pricing,
)
from core.providers.factory import create_engine_provider
from task_logger import LogPhase
from ui import print_key_value, print_status
logger = logging.getLogger(__name__)
DEFAULT_PROVIDER_SMOKE_PROMPT = (
"Reply with one short sentence confirming the provider smoke check works."
)
DEFAULT_PROVIDER_GENERIC_EDIT_SMOKE_CONTENT = "provider smoke ok\n"
DEFAULT_PROVIDER_GENERIC_EDIT_SMOKE_PROMPT = (
"Use the available local tools to overwrite provider-smoke.txt with exactly "
f"{DEFAULT_PROVIDER_GENERIC_EDIT_SMOKE_CONTENT!r}, then finish with a short "
"summary. Do not edit any other file."
)
DEFAULT_PROVIDER_TRANSACTION_BATCH_SMOKE_PROMPT = (
"Transaction batch readiness exercise. Follow these steps EXACTLY, in "
"order:\n"
"1. Call begin_batch with batch_id `provider-batch-smoke`.\n"
"2. Call write_file to overwrite provider-smoke.txt with exactly "
f"{DEFAULT_PROVIDER_GENERIC_EDIT_SMOKE_CONTENT!r}.\n"
"3. Call commit_batch to commit the batch.\n"
"4. Call finish with a short summary. Do not edit any other file.\n"
)
DEFAULT_PROVIDER_SUBAGENT_MERGE_SMOKE_PROMPT = (
"Subagent merge readiness exercise: delegate the prepared "
"transactional_write child tasks, resolve any reported changeset "
"conflicts explicitly, then finish."
)
DEFAULT_PROVIDER_MINI_PIPELINE_TASK = (
"Implement slugify(value: str) in string_tools.py."
)
DEFAULT_PROVIDER_MINI_PIPELINE_TEST_COMMAND = "python -m unittest -q"
PROVIDER_SMOKE_COST_ESTIMATE_INPUT_TOKENS = 10_000
PROVIDER_SMOKE_COST_ESTIMATE_OUTPUT_TOKENS = 2_000
DEFAULT_PROVIDER_MINI_PIPELINE_PLANNER_PROMPT = (
"Plan a tiny Auto Code readiness task for a provider pipeline smoke check.\n\n"
"Task: {task}\n\n"
"Reply with a concise implementation plan. Do not edit files."
)
DEFAULT_PROVIDER_MINI_PIPELINE_CODER_PROMPT = (
"Mini coding readiness task.\n\n"
"Project files:\n"
"- string_tools.py currently has normalize_space(value: str).\n"
"- test_string_tools.py already contains unittest coverage for slugify.\n\n"
"Task: {task}\n\n"
"Acceptance criteria:\n"
"- Add slugify(value: str) to string_tools.py.\n"
"- It lowercases text, trims surrounding whitespace, replaces every run of "
"non-alphanumeric characters with one hyphen, and trims leading/trailing "
"hyphens.\n"
f"- {DEFAULT_PROVIDER_MINI_PIPELINE_TEST_COMMAND} passes.\n\n"
"Planner notes:\n{planner_response}\n\n"
"Use the available local tools to edit the temporary project, then finish "
"with a short summary and tests run."
)
DEFAULT_PROVIDER_MINI_PIPELINE_REVIEW_PROMPT = (
"Review this completed mini Auto Code readiness task.\n\n"
"Task: {task}\n"
f"Verification command: {DEFAULT_PROVIDER_MINI_PIPELINE_TEST_COMMAND}\n"
"Verification exit code: {test_exit_code}\n"
"Verification output:\n{test_output}\n\n"
"Final string_tools.py:\n{implementation}\n\n"
"Reply with one short sentence stating whether the mini task is ready."
)
DEFAULT_PROVIDER_MINI_PIPELINE_RECOVERY_CONTENT = "provider recovery ok\n"
DEFAULT_PROVIDER_MINI_PIPELINE_RECOVERY_INITIAL_CONTENT = "pending recovery\n"
DEFAULT_PROVIDER_MINI_PIPELINE_RECOVERY_PROMPT = (
"Generic Edit recovery readiness exercise. This verifies the runtime's "
"recovery checkpoint, so follow these steps EXACTLY, in order, and do not "
"try to fix or work around anything:\n"
"1. Call write_file to overwrite recovery-target.txt with exactly "
f"{DEFAULT_PROVIDER_MINI_PIPELINE_RECOVERY_CONTENT!r}.\n"
"2. Call read_file on missing-recovery.txt. It does not exist, so the read "
"reports a missing file. This is intentional: do NOT create the file and do "
"NOT resolve the error.\n"
"3. Immediately call finish (do not edit any other file first). The runtime "
"is EXPECTED to block this finish and create a recovery checkpoint — that "
"block is the correct, successful outcome here, not an error to repair.\n"
)
MINI_PIPELINE_INITIAL_STRING_TOOLS = (
'def normalize_space(value: str) -> str:\n return " ".join(value.split())\n'
)
MINI_PIPELINE_TEST_FILE = (
"import unittest\n\n"
"from string_tools import slugify\n\n\n"
"class SlugifyTests(unittest.TestCase):\n"
" def test_slugifies_mixed_text(self):\n"
' self.assertEqual(slugify(" Hello, Auto Code! "), "hello-auto-code")\n\n'
" def test_trims_repeated_separators(self):\n"
' self.assertEqual(slugify("---Already Sluggy---"), "already-sluggy")\n\n\n'
'if __name__ == "__main__":\n'
" unittest.main()\n"
)
def _smoke_content_matches(actual: str, expected: str) -> bool:
"""Compare smoke-file content tolerant of surrounding whitespace.
A capability probe should pass when the model wrote the right content;
a byte-exact match (including the trailing newline) wrongly rejects
models that omit it, e.g. ``provider smoke ok`` vs ``provider smoke
ok\\n``. The semantic content is what the probe is checking.
"""
return actual.strip() == expected.strip()
def _recovery_checkpoint_failure_reason(
initial_status: str, checkpoint_exists: bool
) -> str:
"""Reason for a recovery probe that produced no usable checkpoint.
Embeds the two discriminators so the nightly summary (which keeps only
``reason``) shows *why*: ``initial_status != "error"`` means the model
never triggered the runtime's finish-block (so no checkpoint was due);
``initial_status == "error"`` with ``checkpoint_exists`` False means the
runtime blocked but did not persist the checkpoint (a runtime bug).
"""
return (
"recovery_checkpoint_not_created("
f"initial_status={initial_status},"
f"checkpoint_exists={checkpoint_exists})"
)
def _resume_recovery_failure_reason(
*,
resume_status: str,
content_ok: bool,
recovery_resolved: bool,
guard_status: str,
) -> str:
"""Reason for a recovery-resume that did not come back clean.
Four independent conditions can trip it; embed each so the nightly
summary (which keeps only ``reason``) pinpoints which one — the resume
failed to continue, the recovered content is wrong, the recovery was not
marked resolved, or the workspace guard is not clean.
"""
return (
"resume_recovery_not_clean("
f"resume_status={resume_status},"
f"content_ok={content_ok},"
f"recovery_resolved={recovery_resolved},"
f"guard={guard_status})"
)
DEFAULT_PROVIDER_SMOKE_TIMEOUT_SECONDS = 30.0
PROVIDER_SMOKE_RUNTIME_MODES = (
"analysis_only",
"generic_edit",
"mini_pipeline",
"transaction_batch_probe",
"subagent_merge_probe",
"provider_e2e",
)
PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS = DIRECT_API_PROVIDERS
PROVIDER_RELIABILITY_CASE_ORDER = (
"text_completion",
"generic_edit_tool_loop",
"native_tool_calls",
"tool_results",
"recovery_loop",
"transaction_batches",
"unsupported_tools",
"gateway_model_limitations",
)
PROVIDER_RELIABILITY_NEGATIVE_FIXTURES = {
"openai": {
"surface": "openai_compat",
"unsupported_tools_error": (
"OpenAI tool-call completion failed: Error code: 400 - "
"This model does not support tools."
),
"gateway_model_error": (
"OpenAI tool-call completion failed: Error code: 502 - "
"Bad gateway from upstream model provider."
),
},
"google": {
"surface": "google_gemini",
"unsupported_tools_error": (
"Google tool-call completion failed: 400 function calling is not "
"supported for this model."
),
"gateway_model_error": (
"Google tool-call completion failed: 503 upstream gateway timeout."
),
},
"openrouter": {
"surface": "openrouter_openai_compat",
"unsupported_tools_error": (
"OpenRouter tool-call completion failed: Provider returned 400 "
"unsupported tool_choice for selected model."
),
"gateway_model_error": (
"OpenRouter tool-call completion failed: 502 bad gateway from "
"upstream provider."
),
},
"litellm": {
"surface": "litellm_gateway",
"unsupported_tools_error": (
"LiteLLM tool-call completion failed: UnsupportedParamsError: "
"function calling tools are not supported for this model."
),
"gateway_model_error": (
"LiteLLM tool-call completion failed: upstream gateway 504 timeout."
),
},
"zhipuai": {
"surface": "zhipuai_glm",
"unsupported_tools_error": (
"ZhipuAI tool-call completion failed: function calling is not "
"supported by this model."
),
"gateway_model_error": (
"ZhipuAI tool-call completion failed: 503 upstream connection timeout."
),
},
"ollama": {
"surface": "ollama_openai_compat",
"unsupported_tools_error": (
"Ollama tool-call completion failed: local model does not support tools."
),
"gateway_model_error": (
"Ollama tool-call completion failed: connection refused by local "
"Ollama gateway."
),
},
}
PROVIDER_RELIABILITY_STATUS_RANK = {
"not_covered": 0,
"blocked": 1,
"limited": 2,
"passed": 3,
}
PROVIDER_SMOKE_HISTORY_RELATIVE_PATH = (
AUTO_CODE_RUNTIME_DIR / PROVIDER_SMOKE_HISTORY_FILENAME
)
PROVIDER_SMOKE_HISTORY_MAX_RUNS = 100
PROVIDER_SMOKE_HISTORY_TREND_WINDOW = 5
PROVIDER_E2E_LIVE_FAULT_PROBES_ENV = "AUTO_CODE_PROVIDER_E2E_LIVE_FAULT_PROBES"
PROVIDER_E2E_LIVE_TASKS_ENV = "AUTO_CODE_PROVIDER_E2E_LIVE_TASKS"
PROVIDER_E2E_LIVE_FAULT_CASES = {
"unsupported_tools": {
"suffix": "UNSUPPORTED_TOOLS_ERROR",
"expected_statuses": ("unsupported_tools",),
"runtime_mode": "live_unsupported_tools_probe",
"passed_message": "Live unsupported tool fault probe passed",
"skipped_message": "Live unsupported tool fault probe skipped",
"failed_message": "Live unsupported tool fault probe failed",
},
"gateway_model_limitations": {
"suffix": "GATEWAY_MODEL_ERROR",
"expected_statuses": ("gateway_blocked", "model_blocked"),
"runtime_mode": "live_gateway_model_probe",
"passed_message": "Live gateway/model fault probe passed",
"skipped_message": "Live gateway/model fault probe skipped",
"failed_message": "Live gateway/model fault probe failed",
},
}
# Maps each live-fault case suffix to the matching curated negative-fixture
# key in PROVIDER_RELIABILITY_NEGATIVE_FIXTURES. The opt-in live-fault probes
# prefer genuinely-captured provider errors supplied via env, but fall back to
# these representative signatures so the deterministic classifier probe still
# has coverage in CI without per-run secrets.
PROVIDER_E2E_LIVE_FAULT_BUILTIN_FIXTURE_KEY_BY_SUFFIX = {
"UNSUPPORTED_TOOLS_ERROR": "unsupported_tools_error",
"GATEWAY_MODEL_ERROR": "gateway_model_error",
}
PROVIDER_E2E_LIVE_TASK_FAMILIES = {
"single_file_edit": {
"suffix": "SINGLE_FILE_EDIT_STATUS",
"runtime_mode": "live_task_single_file_edit",
"passed_message": "Live single-file edit task family passed",
"skipped_message": "Live single-file edit task family skipped",
"failed_message": "Live single-file edit task family failed",
},
"multi_step_edit": {
"suffix": "MULTI_STEP_EDIT_STATUS",
"runtime_mode": "live_task_multi_step_edit",
"passed_message": "Live multi-step edit task family passed",
"skipped_message": "Live multi-step edit task family skipped",
"failed_message": "Live multi-step edit task family failed",
},
"recovery_resume": {
"suffix": "RECOVERY_RESUME_STATUS",
"runtime_mode": "live_task_recovery_resume",
"passed_message": "Live recovery/resume task family passed",
"skipped_message": "Live recovery/resume task family skipped",
"failed_message": "Live recovery/resume task family failed",
},
"transaction_batching": {
"suffix": "TRANSACTION_BATCHING_STATUS",
"runtime_mode": "live_task_transaction_batching",
"passed_message": "Live transaction batching task family passed",
"skipped_message": "Live transaction batching task family skipped",
"failed_message": "Live transaction batching task family failed",
},
}
PROVIDER_AUTONOMOUS_READINESS_MIN_STABLE_RUNS = DEFAULT_MIN_STABLE_RUNS
PROVIDER_AUTONOMOUS_READINESS_MAX_HISTORY_AGE_SECONDS = (
DEFAULT_MAX_HISTORY_AGE_DAYS * 24 * 60 * 60
)
PROVIDER_AUTONOMOUS_READINESS_REQUIRED_LIVE_FAULT_CASES = (
DEFAULT_REQUIRED_LIVE_FAULT_CASES
)
PROVIDER_AUTONOMOUS_READINESS_REQUIRED_LIVE_TASK_FAMILIES = (
DEFAULT_REQUIRED_LIVE_TASK_FAMILIES
)
PROVIDER_AUTONOMOUS_PROMOTION_REQUIRED_E2E_RUNS = DEFAULT_REQUIRED_E2E_RUNS
PROVIDER_AUTONOMOUS_READINESS_RECOMMENDATION_REASON_BY_SIGNAL = {
"provider_e2e_failed": "provider_e2e_failed",
"provider_reliability_incomplete": "provider_reliability_incomplete",
"provider_history_latest_failed": "latest_provider_smoke_failed",
"provider_history_unknown": "history_missing",
"provider_history_warming_up": "history_warming_up",
"provider_history_flaky": "history_flaky",
"provider_history_recovering": "history_recovering",
"provider_history_degraded": "history_degraded",
"provider_history_insufficient_runs": "history_insufficient_runs",
"provider_history_stale": "history_stale",
"provider_history_freshness_unknown": "history_freshness_unknown",
"live_fault_probe_evidence_missing": "live_fault_probe_missing",
"live_fault_probe_coverage_incomplete": "live_fault_coverage_incomplete",
"live_task_family_evidence_missing": "live_task_family_missing",
"live_task_family_coverage_incomplete": "live_task_family_coverage_incomplete",
"quality_trend_degrading": "quality_trend_degrading",
"stability_trend_degrading": "stability_trend_degrading",
"safety_trend_degrading": "safety_trend_degrading",
}
@dataclass(frozen=True)
class ProviderSmokeResult:
"""Structured result for one provider smoke check."""
success: bool
provider: str
model: str | None
runtime_mode: str
message: str
response_excerpt: str | None = None
error_details: str | None = None
runtime_diagnostics: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
"""Serialize result for JSON output."""
return asdict(self)
class ProviderSendMessageSession:
"""Expose provider.send_message() as a completion session."""
def __init__(self, provider: Any):
self.provider_name = provider.name
self._provider = provider
async def complete(self, message: str, stream: bool = True):
del stream
async for chunk in self._provider.send_message(message):
yield chunk
def _utc_timestamp() -> str:
"""Return a compact UTC timestamp for provider evidence artifacts."""
return datetime.now(UTC).isoformat().replace("+00:00", "Z")
def _provider_smoke_history_path(project_dir: Path) -> Path:
"""Return the canonical provider smoke history write path."""
return provider_smoke_history_path(project_dir)
def _provider_smoke_history_read_path(project_dir: Path) -> Path:
"""Return the readable provider smoke history path.
Reads tolerate the legacy ``.auto-Codex/`` location so a stale clone
keeps working until ``scripts/migrate_auto_codex_dir.py`` runs.
Writes always go to :func:`provider_smoke_history_path`.
"""
return resolve_provider_smoke_history_path(project_dir)
def _provider_smoke_history_record(
result: ProviderSmokeResult,
*,
timestamp: str | None = None,
) -> dict[str, Any]:
"""Build a compact persisted provider smoke evidence record."""
runtime_diagnostics = result.runtime_diagnostics
reliability = _dict_payload(runtime_diagnostics.get("provider_reliability"))
provider_e2e_suite = _dict_payload(runtime_diagnostics.get("provider_e2e_suite"))
suite_runs = provider_e2e_suite.get("runs")
e2e_case_counts = _provider_e2e_suite_case_counts(suite_runs)
failed_suite_runs = _provider_e2e_failed_suite_runs(suite_runs)
reliability_case_counts = _provider_reliability_case_counts(reliability)
record: dict[str, Any] = {
"timestamp": timestamp or _utc_timestamp(),
"provider": result.provider,
"model": result.model,
"runtime_mode": result.runtime_mode,
"status": "passed" if result.success else "failed",
"message": result.message,
"smoke_scope": runtime_diagnostics.get("smoke_scope"),
"reliability_status": reliability.get("status"),
"passed_case_count": reliability.get("passed_case_count"),
"required_case_count": reliability.get("required_case_count"),
"provider_e2e_status": provider_e2e_suite.get("status"),
**e2e_case_counts,
**reliability_case_counts,
"failed_suite_runs": failed_suite_runs,
}
record.update(
_provider_live_fault_probe_history_record(
_dict_payload(runtime_diagnostics.get("provider_e2e_live_fault_probes"))
)
)
record.update(
_provider_live_task_family_history_record(
_dict_payload(runtime_diagnostics.get("provider_e2e_live_task_families"))
)
)
cost_record = _provider_smoke_cost_record(result)
if cost_record:
record.update(cost_record)
if result.error_details:
record["error_details"] = _response_excerpt(result.error_details, max_chars=240)
record.update(_provider_smoke_promotion_record(result))
return record
def _dict_payload(value: Any) -> dict[str, Any]:
"""Return a dictionary payload or an empty dictionary."""
return value if isinstance(value, dict) else {}
def _provider_e2e_failed_suite_runs(suite_runs: Any) -> list[str]:
"""Return failed provider e2e child runtime modes."""
if not isinstance(suite_runs, list):
return []
return [
str(run.get("runtime_mode") or "unknown")
for run in suite_runs
if isinstance(run, dict) and run.get("status") != "passed"
]
def _provider_live_fault_probe_history_record(
live_fault_probes: dict[str, Any],
) -> dict[str, Any]:
"""Return persisted live fault probe evidence fields."""
record: dict[str, Any] = {}
status = live_fault_probes.get("status")
if isinstance(status, str) and status:
record["live_fault_probe_status"] = status
enabled = live_fault_probes.get("enabled")
if isinstance(enabled, bool):
record["live_fault_probe_enabled"] = enabled
covered_cases = _string_list_payload(live_fault_probes.get("covered_cases"))
if covered_cases:
record["live_fault_probe_covered_cases"] = covered_cases
missing_env = _string_list_payload(live_fault_probes.get("missing_env"))
if missing_env:
record["live_fault_probe_missing_env_count"] = len(missing_env)
return record
def _provider_live_task_family_history_record(
live_task_families: dict[str, Any],
) -> dict[str, Any]:
"""Return persisted live task-family evidence fields."""
record: dict[str, Any] = {}
status = live_task_families.get("status")
if isinstance(status, str) and status:
record["live_task_family_status"] = status
enabled = live_task_families.get("enabled")
if isinstance(enabled, bool):
record["live_task_family_enabled"] = enabled
covered_families = _string_list_payload(live_task_families.get("covered_families"))
if covered_families:
record["live_task_family_covered_families"] = covered_families
failed_families = _string_list_payload(live_task_families.get("failed_families"))
if failed_families:
record["live_task_family_failed_families"] = failed_families
missing_env = _string_list_payload(live_task_families.get("missing_env"))
if missing_env:
record["live_task_family_missing_env_count"] = len(missing_env)
return record
def _provider_smoke_promotion_record(result: ProviderSmokeResult) -> dict[str, Any]:
"""Return per-run promotion evidence that can be persisted in history."""
if result.provider.lower() not in PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS:
return {}
smoke_scope = result.runtime_diagnostics.get("smoke_scope")
if (
result.runtime_mode != "provider_e2e"
and smoke_scope != "direct_api_full_autonomy_e2e"
):
return {}
policy = autonomy_policy_for(result.provider)
required_reliability_cases = list(PROVIDER_RELIABILITY_CASE_ORDER)
passed_reliability_cases = _provider_promotion_passed_reliability_cases(
result.runtime_diagnostics.get("provider_reliability")
)
missing_reliability_cases = [
case
for case in required_reliability_cases
if case not in passed_reliability_cases
]
required_e2e_runs = list(policy.required_e2e_runs)
passed_e2e_runs = _provider_promotion_passed_e2e_runs(
result.runtime_diagnostics.get("provider_e2e_suite")
)
missing_e2e_runs = [run for run in required_e2e_runs if run not in passed_e2e_runs]
return {
"promotion_gate_status": "passed"
if not missing_reliability_cases and not missing_e2e_runs
else "blocked",
"promotion_required_reliability_cases": required_reliability_cases,
"promotion_passed_reliability_cases": passed_reliability_cases,
"promotion_missing_reliability_cases": missing_reliability_cases,
"promotion_required_e2e_runs": required_e2e_runs,
"promotion_passed_e2e_runs": passed_e2e_runs,
"promotion_missing_e2e_runs": missing_e2e_runs,
}
def _provider_e2e_suite_case_counts(suite_runs: Any) -> dict[str, int]:
"""Return per-run e2e case counters from a provider e2e suite."""
if not isinstance(suite_runs, list):
return {}
case_count = 0
passed_case_count = 0
failed_case_count = 0
for run in suite_runs:
if not isinstance(run, dict):
continue
case_count += 1
if run.get("status") == "passed":
passed_case_count += 1
else:
failed_case_count += 1
return {
"e2e_case_count": case_count,
"e2e_passed_case_count": passed_case_count,
"e2e_failed_case_count": failed_case_count,
}
def _provider_reliability_case_counts(reliability: dict[str, Any]) -> dict[str, int]:
"""Return direct-provider reliability case counters from diagnostics."""
return {
"reliability_observed_case_count": _int_payload_value(
reliability,
"observed_case_count",
),
"reliability_passed_case_count": _int_payload_value(
reliability,
"passed_case_count",
),
"reliability_required_case_count": _int_payload_value(
reliability,
"required_case_count",
),
}
def _provider_smoke_cost_record(result: ProviderSmokeResult) -> dict[str, Any]:
"""Return actual token/cost evidence for a provider smoke run when available."""
pricing_model = _provider_smoke_cost_pricing_model(result.model)
if not pricing_model:
return {}
token_usage = _provider_smoke_token_usage_payload(result.runtime_diagnostics)
if token_usage is None:
input_tokens = PROVIDER_SMOKE_COST_ESTIMATE_INPUT_TOKENS
output_tokens = PROVIDER_SMOKE_COST_ESTIMATE_OUTPUT_TOKENS
cost_source = "fixed_token_estimate"
cost_status = "estimated"
else:
input_tokens = token_usage["input_tokens"]
output_tokens = token_usage["output_tokens"]
cost_source = token_usage["source"]
cost_status = "recorded"
cost_usd = calculate_cost(pricing_model, input_tokens, output_tokens)
pricing = get_model_pricing(pricing_model)
return {
"cost_status": cost_status,
"cost_source": cost_source,
"cost_input_tokens": input_tokens,
"cost_output_tokens": output_tokens,
"cost_usd": cost_usd,
"cost_formatted": format_cost(cost_usd),
"cost_pricing_model": pricing_model,
"cost_pricing_provider": pricing.get("provider"),
}
def _provider_smoke_cost_pricing_model(model: Any) -> str | None:
"""Return a known pricing model from provider smoke evidence."""
if not isinstance(model, str):
return None
trimmed = model.strip()
if not trimmed:
return None
if trimmed in MODEL_PRICING and trimmed != "default":
return trimmed
for segment in reversed(trimmed.split("/")):
if segment in MODEL_PRICING and segment != "default":
return segment
return None
def _provider_smoke_token_usage_payload(
runtime_diagnostics: dict[str, Any],
) -> dict[str, int | str] | None:
"""Return normalized token usage evidence from smoke diagnostics."""
candidates: list[tuple[str, Any]] = [
("token_usage", runtime_diagnostics.get("token_usage")),
("usage", runtime_diagnostics.get("usage")),
]
execution = runtime_diagnostics.get("validated_runtime_execution")
if isinstance(execution, dict):
candidates.extend(
[
(
"validated_runtime_execution.token_usage",
execution.get("token_usage"),
),
("validated_runtime_execution.usage", execution.get("usage")),
]
)
for source, payload in candidates:
if not isinstance(payload, dict):
continue
input_tokens = _int_payload_value_from_keys(
payload,
("input_tokens", "prompt_tokens"),
)
output_tokens = _int_payload_value_from_keys(
payload,
("output_tokens", "completion_tokens"),
)
if input_tokens is None or output_tokens is None:
continue
return {
"source": source,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
}
return None
def _int_payload_value_from_keys(
payload: dict[str, Any],
keys: tuple[str, ...],
) -> int | None:
"""Return the first non-negative integer value from any candidate key."""
for key in keys:
value = payload.get(key)
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
return value
return None
def _load_provider_smoke_history(
history_path: Path,
) -> tuple[list[dict[str, Any]], bool]:
"""Load provider smoke history records, returning whether repair was needed."""
if not history_path.exists():
return [], False
try:
payload = json.loads(history_path.read_text(encoding="utf-8"))
except Exception:
return [], True
if not isinstance(payload, dict):
return [], True
runs = payload.get("runs")
if not isinstance(runs, list):
return [], True
return [run for run in runs if isinstance(run, dict)], False
def _provider_smoke_history_streak(
statuses: list[str],
*,
status: str,
) -> int:
"""Return the trailing streak length for a status."""
streak = 0
for run_status in reversed(statuses):
if run_status != status:
break
streak += 1
return streak
def _provider_smoke_history_trend(
runs: list[dict[str, Any]],
) -> dict[str, Any]:
"""Return compact recent-run trend diagnostics for one provider."""
recent_runs = runs[-PROVIDER_SMOKE_HISTORY_TREND_WINDOW:]
statuses = [str(run.get("status") or "unknown") for run in recent_runs]
recent_passed_runs = statuses.count("passed")
recent_failed_runs = statuses.count("failed")
consecutive_passes = _provider_smoke_history_streak(
statuses,
status="passed",
)
consecutive_failures = _provider_smoke_history_streak(
statuses,
status="failed",
)
latest_status = statuses[-1] if statuses else "unknown"
if not statuses:
trend = "provider_history_unknown"
trend_reason = "no_history_runs"
elif len(statuses) == 1:
trend = "provider_history_warming_up"
trend_reason = "single_history_run"
elif recent_failed_runs == 0 and recent_passed_runs == len(statuses):
trend = "provider_history_stable"
trend_reason = "recent_runs_all_passed"
elif latest_status == "failed" and consecutive_failures >= 2:
trend = "provider_history_degraded"
trend_reason = "consecutive_recent_failures"
elif latest_status == "passed" and recent_failed_runs > 0:
trend = "provider_history_recovering"
trend_reason = "latest_run_passed_after_failures"
else:
trend = "provider_history_flaky"
trend_reason = "mixed_recent_results"
return {
"trend": trend,
"trend_reason": trend_reason,
"recent_window": len(recent_runs),
"recent_passed_runs": recent_passed_runs,
"recent_failed_runs": recent_failed_runs,
"consecutive_passes": consecutive_passes,
"consecutive_failures": consecutive_failures,
"recent_runs": _provider_smoke_history_recent_runs(recent_runs),
**_provider_smoke_history_eval_trends(recent_runs),
}
def _provider_smoke_history_recent_runs(
runs: list[dict[str, Any]],
) -> list[dict[str, str]]:
"""Return a compact normalized timeline for the latest provider runs."""
timeline: list[dict[str, str]] = []
fields = (
"timestamp",
"status",
"runtime_mode",
"model",
"reliability_status",
"provider_e2e_status",
"live_fault_probe_status",
"live_task_family_status",
)
for run in runs:
item = {
field: value
for field in fields
if isinstance((value := run.get(field)), str) and value
}
if item:
timeline.append(item)
return timeline
def _provider_smoke_history_provider_stats(
runs: list[dict[str, Any]],
) -> dict[str, dict[str, Any]]:
"""Return per-provider aggregate history stats from persisted records."""
providers: dict[str, dict[str, Any]] = {}
provider_runs: dict[str, list[dict[str, Any]]] = {}
for run in runs:
provider = str(run.get("provider") or "unknown")
status = str(run.get("status") or "unknown")
provider_runs.setdefault(provider, []).append(run)
stats = providers.setdefault(provider, _provider_smoke_empty_provider_stats())
_provider_smoke_history_apply_run_stats(stats, run, status=status)
for provider, stats in providers.items():
stats["live_fault_probe_covered_cases"] = sorted(
stats["live_fault_probe_covered_cases"]
)
stats["live_task_family_covered_families"] = sorted(
stats["live_task_family_covered_families"]
)
stats["live_task_family_failed_families"] = sorted(
stats["live_task_family_failed_families"]
)
stats.update(_provider_smoke_history_trend(provider_runs.get(provider, [])))
stats.update(_provider_smoke_history_metrics(stats))
return providers
def _provider_smoke_empty_provider_stats() -> dict[str, Any]:
"""Return a fresh provider history stats accumulator."""
return {
"total_runs": 0,
"passed_runs": 0,
"failed_runs": 0,
"last_status": "unknown",
"last_runtime_mode": "unknown",
"last_model": None,
"last_run_at": None,
"last_reliability_status": None,
"last_provider_e2e_status": None,
"e2e_case_count": 0,
"e2e_passed_case_count": 0,
"e2e_failed_case_count": 0,
"reliability_observed_case_count": 0,
"reliability_passed_case_count": 0,
"reliability_required_case_count": 0,
"last_live_fault_probe_status": None,
"live_fault_probe_enabled_runs": 0,
"live_fault_probe_passed_runs": 0,
"live_fault_probe_covered_cases": [],
"last_live_task_family_status": None,
"live_task_family_enabled_runs": 0,
"live_task_family_passed_runs": 0,
"live_task_family_covered_families": [],
"live_task_family_failed_families": [],
"last_promotion_gate_status": None,
"promotion_required_reliability_cases": [],
"promotion_passed_reliability_cases": [],
"promotion_missing_reliability_cases": [],
"promotion_required_e2e_runs": [],
"promotion_passed_e2e_runs": [],
"promotion_missing_e2e_runs": [],
}
def _provider_smoke_history_apply_run_stats(
stats: dict[str, Any],
run: dict[str, Any],
*,
status: str,
) -> None:
"""Apply one persisted provider-smoke run to aggregate provider stats."""
stats["total_runs"] += 1
if status == "passed":
stats["passed_runs"] += 1
elif status == "failed":
stats["failed_runs"] += 1
stats["last_status"] = status
stats["last_runtime_mode"] = run.get("runtime_mode")
stats["last_model"] = run.get("model")
stats["last_run_at"] = run.get("timestamp")
stats["last_reliability_status"] = run.get("reliability_status")
stats["last_provider_e2e_status"] = run.get("provider_e2e_status")
_provider_smoke_history_apply_case_stats(stats, run)
_provider_smoke_history_apply_live_fault_stats(stats, run)
_provider_smoke_history_apply_live_task_family_stats(stats, run)
_provider_smoke_history_apply_promotion_stats(stats, run)
_provider_smoke_history_apply_cost_stats(stats, run)
def _provider_smoke_history_apply_case_stats(
stats: dict[str, Any],
run: dict[str, Any],
) -> None:
"""Apply granular e2e and reliability case counters from one run."""
for key in (
"e2e_case_count",
"e2e_passed_case_count",
"e2e_failed_case_count",
"reliability_observed_case_count",
"reliability_passed_case_count",
"reliability_required_case_count",
):
stats[key] = _int_payload_value(stats, key) + _int_payload_value(run, key)
def _provider_smoke_history_apply_live_fault_stats(
stats: dict[str, Any],
run: dict[str, Any],
) -> None:
"""Apply live-fault probe evidence from one persisted run."""
live_fault_probe_status = run.get("live_fault_probe_status")
stats["last_live_fault_probe_status"] = (
live_fault_probe_status
if isinstance(live_fault_probe_status, str) and live_fault_probe_status
else None
)
if run.get("live_fault_probe_enabled") is True:
stats["live_fault_probe_enabled_runs"] += 1
if live_fault_probe_status == "passed":
stats["live_fault_probe_passed_runs"] += 1
existing_cases = stats["live_fault_probe_covered_cases"]
for covered_case in _string_list_payload(run.get("live_fault_probe_covered_cases")):
if covered_case not in existing_cases:
existing_cases.append(covered_case)
def _provider_smoke_history_apply_live_task_family_stats(
stats: dict[str, Any],
run: dict[str, Any],
) -> None:
"""Apply live task-family evidence from one persisted run."""
live_task_family_status = run.get("live_task_family_status")
stats["last_live_task_family_status"] = (
live_task_family_status
if isinstance(live_task_family_status, str) and live_task_family_status
else None
)
if run.get("live_task_family_enabled") is True:
stats["live_task_family_enabled_runs"] = (
int(stats.get("live_task_family_enabled_runs") or 0) + 1
)
if live_task_family_status == "passed":
stats["live_task_family_passed_runs"] = (
int(stats.get("live_task_family_passed_runs") or 0) + 1
)
covered_families = _string_list_payload(
run.get("live_task_family_covered_families")
)
existing_covered = stats["live_task_family_covered_families"]
for covered_family in covered_families:
if covered_family not in existing_covered:
existing_covered.append(covered_family)
failed_families = _string_list_payload(run.get("live_task_family_failed_families"))
existing_failed = stats["live_task_family_failed_families"]
for failed_family in failed_families:
if failed_family not in existing_failed:
existing_failed.append(failed_family)
def _provider_smoke_history_apply_promotion_stats(
stats: dict[str, Any],
run: dict[str, Any],
) -> None:
"""Apply latest direct-provider promotion evidence from one persisted run."""
if "promotion_gate_status" not in run:
return