-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphase2_capacity.py
More file actions
executable file
·2997 lines (2848 loc) · 124 KB
/
Copy pathphase2_capacity.py
File metadata and controls
executable file
·2997 lines (2848 loc) · 124 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
#!/usr/bin/env python3
"""Run a bounded, Mock-only Phase 2 capacity baseline on isolated Compose.
The harness uses PostgreSQL 16, Redis 7, and at least two independent Workers.
It applies an explicit finite governance policy and records machine-readable,
sanitized evidence for worker scaling, exact local backlog admission, fair
cross-Model slices, lease expiry recovery, Redis stop/start, duplicate delivery,
and governance ledger/audit reconciliation. Results describe only the recorded
commit, host, container limits, and Mock configuration; they are not an SLO,
Provider-side admission result, billing statement, or SLA.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import contextlib
import hashlib
import json
import math
import os
import platform
import signal
import statistics
import sys
import time
import traceback
import uuid
from collections.abc import Sequence
from itertools import pairwise
from pathlib import Path
from typing import Any
SCRIPT_DIRECTORY = Path(__file__).resolve().parent
if str(SCRIPT_DIRECTORY) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIRECTORY))
from phase2_acceptance import ( # noqa: E402
PROJECT_PATTERN,
RUN_SNAPSHOT_FIELDS,
TASK_MESSAGE_VERSION,
TASK_STREAM,
AcceptanceFailure,
AcceptanceInterrupted,
Phase2Acceptance,
parse_datetime,
redact_text,
sanitize,
utc_now,
)
CAPACITY_EVIDENCE_SCHEMA_V1 = "llmbenchlab-phase2-capacity-evidence-v1"
CAPACITY_EVIDENCE_SCHEMA_V2 = "llmbenchlab-phase2-capacity-evidence-v2"
EVIDENCE_SCHEMA = CAPACITY_EVIDENCE_SCHEMA_V1
DEFAULT_QUALIFICATION_PROFILE = "capacity-v1"
FORMAL_QUALIFICATION_PROFILE = "P2-local-control-plane-v2"
QUALIFICATION_PROFILES = (
DEFAULT_QUALIFICATION_PROFILE,
FORMAL_QUALIFICATION_PROFILE,
)
FORMAL_V2_ARGUMENTS: dict[str, int | float] = {
"workers": 2,
"runs_per_phase": 4,
"backlog_limit": 4,
"burst_runs": 6,
"submit_concurrency": 6,
"run_concurrency": 1,
"question_quantum": 5,
"mock_delay_seconds": 0.08,
"timeout_seconds": 180,
"lease_seconds": 30,
"heartbeat_seconds": 10,
"worker_poll_seconds": 1,
"worker_max_attempts": 3,
"retry_backoff_base_seconds": 1,
"retry_backoff_cap_seconds": 30,
"worker_shutdown_grace_seconds": 30,
"redis_block_milliseconds": 1000,
"redis_operation_timeout_seconds": 1,
}
DEFAULT_ARTIFACTS_ROOT = Path(".pytest_cache/artifacts/phase2-capacity")
TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled"})
DEMO_QUESTIONS_PER_RUN = 15
RUN_MAX_TOKENS = 64
RUN_INPUT_TOKEN_RESERVATION = 256
RUN_LIFETIME_REQUEST_BUDGET = 100
RUN_LIFETIME_TOKEN_BUDGET = 100_000
RUN_LIFETIME_COST_BUDGET_USD = "100.00000000"
DATABASE_POOL_SIZE = 5
DATABASE_MAX_OVERFLOW = 5
DATABASE_POOL_TIMEOUT_SECONDS = 2.0
READINESS_DATABASE_TIMEOUT_SECONDS = 2.0
WORKER_MAX_ATTEMPTS = 3
WORKER_RETRY_BACKOFF_BASE_SECONDS = 1.0
WORKER_RETRY_BACKOFF_CAP_SECONDS = 30.0
WORKER_SHUTDOWN_GRACE_SECONDS = 30.0
REDIS_BLOCK_MILLISECONDS = 1000
REDIS_OPERATION_TIMEOUT_SECONDS = 1.0
PROVIDER_CREDENTIAL_ENV_KEYS = (
"OPENAI_API_KEY",
"LLMBENCHLAB_DEMO_API_KEY",
"LLMBENCHLAB_REAL_API_KEY",
"TEST_PROVIDER_KEY",
)
COMPOSE_PROJECT_IMAGE_LABELS = frozenset(
{
"com.docker.compose.project",
"com.docker.compose.service",
}
)
def _is_sha256_identity(value: object) -> bool:
return (
isinstance(value, str)
and value.startswith("sha256:")
and len(value) == 71
and all(character in "0123456789abcdef" for character in value[7:])
)
def _is_container_identity(value: object) -> bool:
return (
isinstance(value, str)
and len(value) == 64
and all(character in "0123456789abcdef" for character in value)
)
def image_content_sha256(inspected_image: dict[str, Any]) -> str:
"""Fingerprint executable image content without per-project Compose labels."""
rootfs = inspected_image.get("RootFS")
config = inspected_image.get("Config")
if not isinstance(rootfs, dict) or not isinstance(config, dict):
raise AcceptanceFailure("docker image inspect omitted RootFS or Config")
layers = rootfs.get("Layers")
if (
not isinstance(layers, list)
or not layers
or not all(_is_sha256_identity(layer) for layer in layers)
):
raise AcceptanceFailure("docker image inspect returned invalid RootFS layers")
stable_config = dict(config)
labels = config.get("Labels")
if labels is not None:
if not isinstance(labels, dict):
raise AcceptanceFailure("docker image inspect returned invalid Config.Labels")
stable_config["Labels"] = {
key: value for key, value in labels.items() if key not in COMPOSE_PROJECT_IMAGE_LABELS
}
payload = {
"architecture": inspected_image.get("Architecture"),
"os": inspected_image.get("Os"),
"variant": inspected_image.get("Variant"),
"rootfs_layers": layers,
"config": stable_config,
}
try:
encoded = json.dumps(
payload,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
allow_nan=False,
).encode("utf-8")
except (TypeError, ValueError) as exc:
raise AcceptanceFailure("docker image content was not canonical JSON") from exc
return hashlib.sha256(encoded).hexdigest()
def reconciliation_expectations(
*,
runs_per_phase: int,
backlog_limit: int,
formal_slo_v2: bool = False,
) -> tuple[dict[str, int], dict[str, int], dict[str, int]]:
"""Derive terminal ledger counts from the accepted capacity workload."""
backlog_groups = 3 if formal_slo_v2 else 2
completed_runs = 2 * runs_per_phase + backlog_groups * backlog_limit + 2
settled_actual = completed_runs * DEMO_QUESTIONS_PER_RUN
reservations = settled_actual + 1
return (
{
"policies": 2,
"active_policies": 1,
"runs": completed_runs,
"responses": settled_actual,
"distinct_run_question_responses": settled_actual,
"question_executions": settled_actual,
"reservations": reservations,
"failed_attempt_count": 1,
"question_error_count": 0,
},
{
"settled_actual": settled_actual,
"settled_conservative": 1,
},
{
"provider_attempt_reserved": reservations,
"provider_attempt_send_started": reservations,
"provider_attempt_settled": reservations,
},
)
(
EXPECTED_RECONCILIATION_COUNTS,
EXPECTED_RESERVATION_STATES,
EXPECTED_PROVIDER_ATTEMPT_AUDIT_COUNTS,
) = reconciliation_expectations(runs_per_phase=4, backlog_limit=4)
RECONCILIATION_ZERO_FIELDS = (
"active_reservations",
"scope_active_reservations",
"scope_reserved_requests",
"scope_reserved_input_tokens",
"scope_reserved_output_tokens",
"minute_reserved_requests",
"minute_reserved_input_tokens",
"minute_reserved_output_tokens",
"overdrawn_scopes",
"duplicate_operation_keys",
"duplicate_response_questions",
"duplicate_audit_event_keys",
"active_runs",
"missing_scope_projection_rows",
"extra_scope_projection_rows",
"scope_projection_field_drift",
"missing_minute_projection_rows",
"extra_minute_projection_rows",
"minute_projection_field_drift",
)
# This deliberately mirrors GovernanceRepository._scope_fact_source() and
# _scope_fact_aggregates(). The acceptance query remains independent of the ORM
# projection so a bug in projection maintenance cannot validate itself.
GOVERNANCE_RECONCILIATION_SQL = """
WITH scope_facts AS MATERIALIZED (
SELECT
scope_ids.scope_id,
reservation.policy_id,
reservation.window_start,
reservation.state,
reservation.reserved_input_tokens,
reservation.reserved_output_tokens,
reservation.reserved_cost_usd,
reservation.actual_input_tokens,
reservation.actual_output_tokens,
reservation.actual_cost_usd,
(reservation.run_id IS NULL OR run.input_token_reservation IS NOT NULL)
AS input_reservation_is_explicit
FROM provider_call_reservations AS reservation
LEFT JOIN evaluation_runs AS run ON run.id = reservation.run_id
CROSS JOIN LATERAL (
VALUES
(reservation.global_scope_id),
(reservation.provider_scope_id),
(reservation.model_scope_id),
(reservation.run_scope_id)
) AS scope_ids(scope_id)
WHERE scope_ids.scope_id IS NOT NULL
),
derived_scopes AS MATERIALIZED (
SELECT
scope_id,
count(*) FILTER (WHERE state IN ('reserved', 'send_started'))
AS active_reservations,
count(*) FILTER (WHERE state = 'reserved') AS reserved_requests,
count(*) FILTER (
WHERE state IN ('send_started', 'settled_actual', 'settled_conservative')
) AS consumed_requests,
COALESCE(sum(reserved_input_tokens) FILTER (
WHERE state IN ('reserved', 'send_started')
), 0) AS reserved_input_tokens,
COALESCE(sum(reserved_output_tokens) FILTER (
WHERE state IN ('reserved', 'send_started')
), 0) AS reserved_output_tokens,
COALESCE(sum(reserved_cost_usd) FILTER (
WHERE state IN ('reserved', 'send_started')
), 0) AS reserved_cost_usd,
COALESCE(sum(actual_input_tokens) FILTER (
WHERE state IN ('settled_actual', 'settled_conservative')
), 0) AS consumed_input_tokens,
COALESCE(sum(actual_output_tokens) FILTER (
WHERE state IN ('settled_actual', 'settled_conservative')
), 0) AS consumed_output_tokens,
COALESCE(sum(actual_cost_usd) FILTER (
WHERE state IN ('settled_actual', 'settled_conservative')
), 0) AS consumed_cost_usd,
COALESCE(bool_or(
state IN ('settled_actual', 'settled_conservative')
AND (
(
input_reservation_is_explicit
AND
reserved_input_tokens IS NOT NULL
AND actual_input_tokens IS NOT NULL
AND actual_input_tokens > reserved_input_tokens
)
OR (
reserved_output_tokens IS NOT NULL
AND actual_output_tokens IS NOT NULL
AND actual_output_tokens > reserved_output_tokens
)
OR (
input_reservation_is_explicit
AND
reserved_cost_usd IS NOT NULL
AND actual_cost_usd IS NOT NULL
AND actual_cost_usd > reserved_cost_usd
)
)
), false) AS overdrawn
FROM scope_facts
GROUP BY scope_id
),
derived_minutes AS MATERIALIZED (
SELECT
scope_id,
policy_id,
window_start,
count(*) FILTER (WHERE state = 'reserved') AS reserved_requests,
count(*) FILTER (
WHERE state IN ('send_started', 'settled_actual', 'settled_conservative')
) AS consumed_requests,
COALESCE(sum(reserved_input_tokens) FILTER (
WHERE state IN ('reserved', 'send_started')
), 0) AS reserved_input_tokens,
COALESCE(sum(reserved_output_tokens) FILTER (
WHERE state IN ('reserved', 'send_started')
), 0) AS reserved_output_tokens,
COALESCE(sum(actual_input_tokens) FILTER (
WHERE state IN ('settled_actual', 'settled_conservative')
), 0) AS consumed_input_tokens,
COALESCE(sum(actual_output_tokens) FILTER (
WHERE state IN ('settled_actual', 'settled_conservative')
), 0) AS consumed_output_tokens
FROM scope_facts
GROUP BY scope_id, policy_id, window_start
)
SELECT json_build_object(
'policies', (SELECT count(*) FROM governance_policies),
'active_policies', (SELECT count(*) FROM governance_policies WHERE is_active),
'runs', (SELECT count(*) FROM evaluation_runs),
'responses', (SELECT count(*) FROM evaluation_responses),
'distinct_run_question_responses', (
SELECT count(*) FROM (
SELECT run_id, question_id FROM evaluation_responses GROUP BY run_id, question_id
) distinct_responses
),
'duplicate_response_questions', (
SELECT count(*) FROM (
SELECT run_id, question_id FROM evaluation_responses
GROUP BY run_id, question_id HAVING count(*) > 1
) duplicates
),
'question_executions', (SELECT count(*) FROM question_executions),
'reservations', (SELECT count(*) FROM provider_call_reservations),
'reservation_states', COALESCE((
SELECT json_object_agg(state, count) FROM (
SELECT state, count(*) AS count
FROM provider_call_reservations GROUP BY state ORDER BY state
) states
), '{}'::json),
'active_reservations', (
SELECT count(*) FROM provider_call_reservations
WHERE state IN ('reserved', 'send_started')
),
'scope_active_reservations', (
SELECT COALESCE(sum(active_reservations), 0) FROM governance_scopes
),
'scope_reserved_requests', (
SELECT COALESCE(sum(reserved_requests), 0) FROM governance_scopes
),
'scope_reserved_input_tokens', (
SELECT COALESCE(sum(reserved_input_tokens), 0) FROM governance_scopes
),
'scope_reserved_output_tokens', (
SELECT COALESCE(sum(reserved_output_tokens), 0) FROM governance_scopes
),
'minute_reserved_requests', (
SELECT COALESCE(sum(reserved_requests), 0) FROM governance_minute_buckets
),
'minute_reserved_input_tokens', (
SELECT COALESCE(sum(reserved_input_tokens), 0) FROM governance_minute_buckets
),
'minute_reserved_output_tokens', (
SELECT COALESCE(sum(reserved_output_tokens), 0) FROM governance_minute_buckets
),
'overdrawn_scopes', (SELECT count(*) FROM governance_scopes WHERE overdrawn),
'missing_scope_projection_rows', (
SELECT count(*) FROM derived_scopes AS derived
LEFT JOIN governance_scopes AS materialized ON materialized.id = derived.scope_id
WHERE materialized.id IS NULL
),
'extra_scope_projection_rows', (
SELECT count(*) FROM governance_scopes AS materialized
LEFT JOIN derived_scopes AS derived ON derived.scope_id = materialized.id
WHERE derived.scope_id IS NULL
),
'scope_projection_field_drift', (
SELECT count(*) FROM governance_scopes AS materialized
JOIN derived_scopes AS derived ON derived.scope_id = materialized.id
WHERE
materialized.active_reservations IS DISTINCT FROM derived.active_reservations
OR materialized.reserved_requests IS DISTINCT FROM derived.reserved_requests
OR materialized.consumed_requests IS DISTINCT FROM derived.consumed_requests
OR materialized.reserved_input_tokens IS DISTINCT FROM derived.reserved_input_tokens
OR materialized.reserved_output_tokens IS DISTINCT FROM derived.reserved_output_tokens
OR materialized.reserved_cost_usd IS DISTINCT FROM derived.reserved_cost_usd
OR materialized.consumed_input_tokens IS DISTINCT FROM derived.consumed_input_tokens
OR materialized.consumed_output_tokens IS DISTINCT FROM derived.consumed_output_tokens
OR materialized.consumed_cost_usd IS DISTINCT FROM derived.consumed_cost_usd
OR materialized.overdrawn IS DISTINCT FROM derived.overdrawn
),
'missing_minute_projection_rows', (
SELECT count(*) FROM derived_minutes AS derived
LEFT JOIN governance_minute_buckets AS materialized
ON materialized.scope_id = derived.scope_id
AND materialized.policy_id = derived.policy_id
AND materialized.window_start = derived.window_start
WHERE materialized.id IS NULL
),
'extra_minute_projection_rows', (
SELECT count(*) FROM governance_minute_buckets AS materialized
LEFT JOIN derived_minutes AS derived
ON derived.scope_id = materialized.scope_id
AND derived.policy_id = materialized.policy_id
AND derived.window_start = materialized.window_start
WHERE derived.scope_id IS NULL
),
'minute_projection_field_drift', (
SELECT count(*) FROM governance_minute_buckets AS materialized
JOIN derived_minutes AS derived
ON derived.scope_id = materialized.scope_id
AND derived.policy_id = materialized.policy_id
AND derived.window_start = materialized.window_start
WHERE
materialized.reserved_requests IS DISTINCT FROM derived.reserved_requests
OR materialized.consumed_requests IS DISTINCT FROM derived.consumed_requests
OR materialized.reserved_input_tokens IS DISTINCT FROM derived.reserved_input_tokens
OR materialized.reserved_output_tokens IS DISTINCT FROM derived.reserved_output_tokens
OR materialized.consumed_input_tokens IS DISTINCT FROM derived.consumed_input_tokens
OR materialized.consumed_output_tokens IS DISTINCT FROM derived.consumed_output_tokens
),
'duplicate_operation_keys', (
SELECT count(*) FROM (
SELECT operation_key FROM provider_call_reservations
GROUP BY operation_key HAVING count(*) > 1
) duplicates
),
'audit_events', (SELECT count(*) FROM audit_events),
'audit_event_types', COALESCE((
SELECT json_object_agg(event_type, count) FROM (
SELECT event_type, count(*) AS count
FROM audit_events GROUP BY event_type ORDER BY event_type
) types
), '{}'::json),
'duplicate_audit_event_keys', (
SELECT count(*) FROM (
SELECT event_key FROM audit_events GROUP BY event_key HAVING count(*) > 1
) duplicates
),
'active_runs', (
SELECT count(*) FROM evaluation_runs WHERE status IN ('pending', 'running')
),
'failed_attempt_count', (
SELECT COALESCE(sum(failed_attempt_count), 0) FROM evaluation_runs
),
'question_error_count', (
SELECT count(*) FROM evaluation_responses WHERE error_type IS NOT NULL
)
)::text;
"""
def _reconciliation_integer(
snapshot: dict[str, Any],
field: str,
*,
context: str = "reconciliation",
) -> int:
value = snapshot.get(field)
if type(value) is not int:
raise AcceptanceFailure(f"{context}.{field} must be an integer")
return value
def validate_governance_reconciliation_snapshot(
snapshot: dict[str, Any],
*,
expected_counts: dict[str, int] | None = None,
expected_reservation_states: dict[str, int] | None = None,
expected_provider_attempt_audit_counts: dict[str, int] | None = None,
) -> None:
"""Enforce the configured workload's ledger and projection invariants."""
expected_counts = expected_counts or EXPECTED_RECONCILIATION_COUNTS
expected_reservation_states = expected_reservation_states or EXPECTED_RESERVATION_STATES
expected_provider_attempt_audit_counts = (
expected_provider_attempt_audit_counts or EXPECTED_PROVIDER_ATTEMPT_AUDIT_COUNTS
)
for field in RECONCILIATION_ZERO_FIELDS:
value = _reconciliation_integer(snapshot, field)
if value != 0:
raise AcceptanceFailure(f"governance reconciliation drift: {field}={value}")
for field, expected in expected_counts.items():
value = _reconciliation_integer(snapshot, field)
if value != expected:
raise AcceptanceFailure(
f"governance reconciliation count drift: {field}={value}, expected={expected}"
)
if snapshot["distinct_run_question_responses"] != snapshot["responses"]:
raise AcceptanceFailure("Response run/question cardinality drift")
reservation_states = snapshot.get("reservation_states")
if not isinstance(reservation_states, dict):
raise AcceptanceFailure("reconciliation.reservation_states must be an object")
for state in reservation_states:
_reconciliation_integer(
reservation_states,
state,
context="reconciliation.reservation_states",
)
if reservation_states != expected_reservation_states:
raise AcceptanceFailure("Provider reservation terminal-state counts drift")
audit_event_types = snapshot.get("audit_event_types")
if not isinstance(audit_event_types, dict):
raise AcceptanceFailure("reconciliation.audit_event_types must be an object")
for event_type, expected in expected_provider_attempt_audit_counts.items():
observed = _reconciliation_integer(
audit_event_types,
event_type,
context="reconciliation.audit_event_types",
)
if observed != expected:
raise AcceptanceFailure(
f"Provider attempt audit count drift: {event_type}={observed}, expected={expected}"
)
if _reconciliation_integer(snapshot, "audit_events") <= 0:
raise AcceptanceFailure("capacity evidence did not produce typed audit events")
def finite_capacity_policy(
*,
backlog_limit: int,
question_quantum: int,
) -> dict[str, int | str]:
"""Return the explicit finite policy used by every capacity scenario."""
return {
"global_concurrency_limit": 32,
"provider_concurrency_limit": 32,
"model_concurrency_limit": 16,
"run_concurrency_limit": 4,
"global_requests_per_minute": 100_000,
"provider_requests_per_minute": 100_000,
"model_requests_per_minute": 50_000,
"run_requests_per_minute": 1_000,
"global_tokens_per_minute": 100_000_000,
"provider_tokens_per_minute": 100_000_000,
"model_tokens_per_minute": 50_000_000,
"run_tokens_per_minute": 1_000_000,
"global_lifetime_request_budget": 100_000,
"global_lifetime_token_budget": 100_000_000,
"global_lifetime_cost_budget_usd": "1000.00000000",
"run_lifetime_request_budget": RUN_LIFETIME_REQUEST_BUDGET,
"run_lifetime_token_budget": RUN_LIFETIME_TOKEN_BUDGET,
"run_lifetime_cost_budget_usd": RUN_LIFETIME_COST_BUDGET_USD,
"backlog_limit": backlog_limit,
"question_quantum": question_quantum,
}
def summarize_submissions(
submissions: Sequence[dict[str, Any]],
*,
duration_seconds: float,
) -> dict[str, Any]:
"""Preserve accepted payloads and exact status-bearing rejection evidence."""
status_counts: dict[str, int] = {}
accepted: list[dict[str, Any]] = []
rejected: list[dict[str, Any]] = []
for submission in submissions:
status_code = int(submission["status_code"])
status_key = str(status_code)
status_counts[status_key] = status_counts.get(status_key, 0) + 1
payload = dict(submission["payload"])
if status_code == 202:
accepted.append(payload)
else:
rejected.append({"status_code": status_code, "payload": payload})
return {
"requested": len(submissions),
"accepted": accepted,
"rejected": rejected,
"status_counts": status_counts,
"duration_seconds": round(duration_seconds, 6),
"request_latency_seconds": distribution(
[float(item["elapsed_seconds"]) for item in submissions]
),
}
def cooperative_scheduling_summary(
final_runs: Sequence[dict[str, Any]],
audit_events: dict[str, Sequence[dict[str, Any]]],
) -> dict[str, Any]:
"""Summarize the durable claim/yield proof for bounded Run slices."""
per_run: list[dict[str, Any]] = []
for run in final_runs:
run_id = str(run["id"])
events = audit_events.get(run_id, ())
per_run.append(
{
"run_id": run_id,
"dispatch_count": int(run.get("dispatch_count") or 0),
"claim_events": sum(event.get("event_type") == "run_claimed" for event in events),
"cooperative_yield_events": sum(
event.get("event_type") == "run_yielded" for event in events
),
}
)
return {
"all_runs_dispatched_more_than_once": bool(per_run)
and all(item["dispatch_count"] > 1 for item in per_run),
"all_runs_yielded": bool(per_run)
and all(item["cooperative_yield_events"] > 0 for item in per_run),
"claim_events": sum(item["claim_events"] for item in per_run),
"cooperative_yield_events": sum(item["cooperative_yield_events"] for item in per_run),
"per_run": per_run,
}
def fairness_ordering_summary(
*,
high_run_ids: Sequence[str],
low_run_id: str,
audit_events: dict[str, Sequence[dict[str, Any]]],
observation: dict[str, Any],
) -> dict[str, Any]:
"""Build ordered evidence that a low-volume Model received an early slice."""
high_ids = set(high_run_ids)
ordered: list[dict[str, Any]] = []
for run_id in (*high_run_ids, low_run_id):
for event in audit_events.get(run_id, ()):
event_type = str(event.get("event_type") or "")
if event_type not in {"run_claimed", "run_yielded", "run_terminal"}:
continue
ordered.append(
{
"event_id": str(event["id"]),
"event_type": event_type,
"occurred_at": str(event["occurred_at"]),
"run_id": run_id,
"role": "low_volume" if run_id == low_run_id else "high_volume",
}
)
ordered.sort(key=lambda event: (parse_datetime(event["occurred_at"]), event["event_id"]))
low_claim_times = [
parse_datetime(event["occurred_at"])
for event in ordered
if event["run_id"] == low_run_id and event["event_type"] == "run_claimed"
]
high_terminal_times = [
parse_datetime(event["occurred_at"])
for event in ordered
if event["run_id"] in high_ids and event["event_type"] == "run_terminal"
]
low_observed = dict(observation["low_run"])
high_observed = [dict(run) for run in observation["high_runs"]]
return {
"low_volume_claim_observed": bool(low_claim_times),
"low_volume_slice_observed": int(low_observed.get("completed_questions") or 0) > 0,
"high_volume_incomplete_at_low_slice": sum(
run.get("status") not in TERMINAL_STATUSES for run in high_observed
),
"low_claim_before_high_backlog_drained": bool(low_claim_times)
and bool(high_terminal_times)
and min(low_claim_times) < max(high_terminal_times),
"observation": {
"low_run": low_observed,
"high_runs": high_observed,
},
"ordered_events": ordered,
}
def percentile(values: Sequence[float], percentage: float) -> float:
"""Return a linearly interpolated percentile for a non-empty sample."""
if not values:
raise ValueError("percentile requires at least one sample")
if not 0 <= percentage <= 100:
raise ValueError("percentage must be between 0 and 100")
ordered = sorted(float(value) for value in values)
if len(ordered) == 1:
return ordered[0]
position = (len(ordered) - 1) * percentage / 100
lower = int(position)
upper = min(lower + 1, len(ordered) - 1)
fraction = position - lower
return ordered[lower] + (ordered[upper] - ordered[lower]) * fraction
def distribution(values: Sequence[float]) -> dict[str, int | float | None]:
"""Summarize a latency or count sample without retaining every observation."""
if not values:
return {
"count": 0,
"min": None,
"mean": None,
"p50": None,
"p95": None,
"p99": None,
"max": None,
}
numeric = [float(value) for value in values]
return {
"count": len(numeric),
"min": round(min(numeric), 6),
"mean": round(statistics.fmean(numeric), 6),
"p50": round(percentile(numeric, 50), 6),
"p95": round(percentile(numeric, 95), 6),
"p99": round(percentile(numeric, 99), 6),
"max": round(max(numeric), 6),
}
def nonnegative_utc_elapsed_seconds(started_at: str, finished_at: str) -> float:
"""Return a finite non-negative duration derived from two UTC facts."""
seconds = (parse_datetime(finished_at) - parse_datetime(started_at)).total_seconds()
if not math.isfinite(seconds) or seconds < 0:
raise ValueError("UTC duration must be finite and non-negative")
return round(seconds, 6)
def first_claim_at_or_after(
audit_events: Sequence[dict[str, Any]],
not_before: str,
) -> dict[str, Any]:
"""Return the first typed claim whose durable occurrence is not before a DB fact."""
threshold = parse_datetime(not_before)
candidates = [
event
for event in audit_events
if event.get("event_type") == "run_claimed"
and isinstance(event.get("occurred_at"), str)
and parse_datetime(str(event["occurred_at"])) >= threshold
]
if not candidates:
raise ValueError("no typed run_claimed event occurred at or after the threshold")
return min(
candidates,
key=lambda event: (parse_datetime(str(event["occurred_at"])), str(event.get("id") or "")),
)
def _validated_worker_owner(
worker_id: object,
validated_workers: dict[str, dict[str, Any]],
) -> str:
"""Parse an exact production Worker owner and map it to inspected runtime facts."""
if not isinstance(worker_id, str):
raise AcceptanceFailure("burst claim omitted a typed Worker owner")
parts = worker_id.split(":")
if len(parts) != 4 or parts[0] != "worker":
raise AcceptanceFailure("burst claim Worker owner did not use the exact runtime format")
hostname, pid_text, instance_text = parts[1:]
try:
pid = int(pid_text)
instance = uuid.UUID(instance_text)
except (ValueError, AttributeError) as exc:
raise AcceptanceFailure("burst claim Worker owner was malformed") from exc
if (
pid <= 0
or pid > 2_147_483_647
or pid_text != str(pid)
or instance.version != 4
or str(instance) != instance_text
):
raise AcceptanceFailure("burst claim Worker owner was not canonical")
if hostname not in validated_workers:
raise AcceptanceFailure("burst claim owner did not map to a validated Worker")
return hostname
def burst_worker_participation(
*,
accepted_run_ids: Sequence[str],
audit_events: dict[str, Sequence[dict[str, Any]]],
worker_state: Sequence[dict[str, Any]],
project: str,
backlog_ready_at: str,
) -> dict[str, Any]:
"""Return raw, independently checkable claim ownership for one formal burst."""
accepted = set(accepted_run_ids)
if len(accepted) != len(accepted_run_ids) or set(audit_events) != accepted:
raise AcceptanceFailure("burst claim evidence did not match the accepted Run set")
if len(worker_state) != 2:
raise AcceptanceFailure("formal burst did not validate exactly two Workers")
validated: dict[str, dict[str, Any]] = {}
for worker in worker_state:
hostname = worker.get("hostname")
container_id = worker.get("id")
if (
not isinstance(hostname, str)
or not hostname
or ":" in hostname
or any(character.isspace() or ord(character) < 32 for character in hostname)
or not _is_container_identity(container_id)
or worker.get("project") != project
or worker.get("service") != "worker"
or worker.get("status") != "running"
or worker.get("health") != "healthy"
):
raise AcceptanceFailure("formal burst Worker runtime metadata was invalid")
if hostname in validated:
raise AcceptanceFailure("formal burst Worker runtime identities were not unique")
validated[hostname] = {
"container_id": container_id,
"hostname": hostname,
}
threshold = parse_datetime(backlog_ready_at)
claims: list[dict[str, str]] = []
owner_ids: set[str] = set()
mapped_workers: set[str] = set()
for run_id in accepted_run_ids:
for event in audit_events[run_id]:
if event.get("event_type") != "run_claimed":
continue
occurred_at = event.get("occurred_at")
if not isinstance(occurred_at, str) or parse_datetime(occurred_at) < threshold:
continue
worker_id = event.get("worker_id")
mapped_hostname = _validated_worker_owner(worker_id, validated)
owner_ids.add(str(worker_id))
mapped_workers.add(mapped_hostname)
claims.append(
{
"run_id": run_id,
"worker_id": str(worker_id),
"occurred_at": occurred_at,
}
)
claims.sort(key=lambda item: (parse_datetime(item["occurred_at"]), item["run_id"]))
if {claim["run_id"] for claim in claims} != accepted:
raise AcceptanceFailure("formal burst did not retain a boundary claim for every Run")
if len(owner_ids) != 2 or len(mapped_workers) != 2:
raise AcceptanceFailure("formal burst did not prove exactly two distinct claim Workers")
return {
"validated_workers": sorted(validated.values(), key=lambda item: item["container_id"]),
"claims": claims,
"distinct_claim_workers": len(owner_ids),
"all_claim_workers_validated": True,
}
def formal_worker_state_witness(
worker_state: Sequence[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Project validated formal Worker metadata onto the consumer contract."""
fields = ("id", "hostname", "project", "service", "status", "health")
return [{field: worker[field] for field in fields} for worker in worker_state]
def burst_segmented_timing(
*,
final_runs: Sequence[dict[str, Any]],
audit_events: dict[str, Sequence[dict[str, Any]]],
participation: dict[str, Any],
suspend_completed_at: str,
backlog_ready_at: str,
restore_completed_at: str,
suspend_seconds: float,
backlog_build_seconds: float,
restore_command_seconds: float,
drain_seconds: float,
) -> dict[str, Any]:
"""Keep UTC durable facts and process-monotonic durations in separate domains."""
claims = list(participation["claims"])
first_claim = min(claims, key=lambda item: parse_datetime(item["occurred_at"]))
first_by_owner: dict[str, dict[str, str]] = {}
for claim in claims:
first_by_owner.setdefault(claim["worker_id"], claim)
all_workers_first_claim = max(
first_by_owner.values(), key=lambda item: parse_datetime(item["occurred_at"])
)
accepted = {str(run["id"]) for run in final_runs}
threshold = parse_datetime(backlog_ready_at)
claim_or_yield: list[dict[str, str]] = []
for run_id in sorted(accepted):
for event in audit_events[run_id]:
event_type = event.get("event_type")
occurred_at = event.get("occurred_at")
if (
event_type in {"run_claimed", "run_yielded"}
and isinstance(occurred_at, str)
and parse_datetime(occurred_at) >= threshold
):
claim_or_yield.append(
{
"run_id": run_id,
"event_type": str(event_type),
"occurred_at": occurred_at,
}
)
claim_or_yield.sort(
key=lambda item: (parse_datetime(item["occurred_at"]), item["run_id"], item["event_type"])
)
adjacent_gaps = [
nonnegative_utc_elapsed_seconds(previous["occurred_at"], current["occurred_at"])
for previous, current in pairwise(claim_or_yield)
]
claims_by_run: dict[str, list[dict[str, str]]] = {run_id: [] for run_id in accepted}
for claim in claims:
claims_by_run[claim["run_id"]].append(claim)
run_timings: list[dict[str, Any]] = []
for run in sorted(final_runs, key=lambda item: str(item["id"])):
run_id = str(run["id"])
finished_at = run.get("finished_at")
if not isinstance(finished_at, str) or not claims_by_run[run_id]:
raise AcceptanceFailure("formal burst Run timing facts were incomplete")
run_first_claim = min(
claims_by_run[run_id], key=lambda item: parse_datetime(item["occurred_at"])
)["occurred_at"]
run_timings.append(
{
"run_id": run_id,
"first_claim_at": run_first_claim,
"finished_at": finished_at,
"duration_seconds": nonnegative_utc_elapsed_seconds(run_first_claim, finished_at),
}
)
first_claim_to_finish = [float(item["duration_seconds"]) for item in run_timings]
return {
"clock_domains": {
"monotonic_seconds": "process_monotonic",
"durable_utc": "database_utc",
},
"monotonic_seconds": {
"suspend": round(suspend_seconds, 6),
"backlog_build": round(backlog_build_seconds, 6),
"restore_command": round(restore_command_seconds, 6),
"drain": round(drain_seconds, 6),
},
"durable_utc": {
"suspend_completed_at": suspend_completed_at,
"backlog_ready_at": backlog_ready_at,
"restore_completed_at": restore_completed_at,
"first_claim_at": first_claim["occurred_at"],
"all_workers_first_claim_at": all_workers_first_claim["occurred_at"],
"claim_or_yield_events": claim_or_yield,
"run_first_claim_to_finish": run_timings,
},
"durable_seconds": {
"backlog_ready_to_first_claim": nonnegative_utc_elapsed_seconds(
backlog_ready_at, first_claim["occurred_at"]
),
"backlog_ready_to_all_workers_first_claim": nonnegative_utc_elapsed_seconds(
backlog_ready_at, all_workers_first_claim["occurred_at"]
),
"adjacent_claim_or_yield_gap": {
**distribution(adjacent_gaps),
"samples": adjacent_gaps,
},
"first_claim_to_finish": {
**distribution(first_claim_to_finish),
"samples": first_claim_to_finish,
},
},
}
def validate_arguments(args: argparse.Namespace) -> None:
if args.workers < 2:
raise ValueError("--workers must be at least 2")
if not 1 <= args.runs_per_phase <= 100: