forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource_release.py
More file actions
2006 lines (1834 loc) · 69.9 KB
/
Copy pathsource_release.py
File metadata and controls
2006 lines (1834 loc) · 69.9 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
"""Strict source-change approval, publication, and rollback receipts.
The re-verification decision ledger is intentionally not a release mechanism.
This module adds three separate evidence records around it. Validation is
read-only: it never adopts a source-state receipt, clears a browser hold,
changes a rule, runs Git, deploys a build, or performs a rollback.
Committed templates remain ``not_run`` and may keep every evidence binding
null. A bound prepared set can be generated only from an open, validated
worklist and its complete decision-ledger shape. A completed approval further
requires every decision entry to be resolved; publication and rollback each
require their own later receipt and a separately validated reviewed
source-state snapshot.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import stat
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import UTC, date, datetime, timedelta
from pathlib import Path
from types import MappingProxyType
from typing import Any
from urllib.parse import urlsplit
from .harness.runner import load_golden
from .harness.watch import load_sources
from .review_queue import (
DECISION_DISPOSITIONS,
DECISION_STATUSES,
ReadinessReviewContext,
ReviewDecision,
ReviewDecisionLedger,
ReviewWorklist,
build_review_worklist,
)
from .screening import load_rules
from .source_state import (
SourceStateSnapshot,
source_state_fingerprint,
validate_source_state_snapshot,
)
RECEIPT_SCHEMA_VERSION = 1
MAX_RECEIPT_BYTES = 262_144
APPROVAL_STATUSES = ("not_run", "complete")
APPROVAL_OUTCOMES = ("approved_for_publication", "rejected")
PUBLICATION_STATUSES = ("not_run", "complete")
ROLLBACK_STATUSES = ("not_run", "complete")
HOLD_STATES = ("clear_in_source_state", "retained_in_source_state")
ROLLBACK_REASONS = (
"controlled_rehearsal",
"content_defect",
"deployment_verification_failure",
"functional_regression",
)
SOURCE_RESOLUTIONS = ("adopt_observed", "restore_recorded", "retain_hold")
APPROVAL_CLAIM_BOUNDARY = (
"This receipt is evidence metadata only. It does not clear a source-review "
"hold, adopt source state, approve legal meaning, publish a build, or "
"authenticate the declared reviewer authority or external evidence."
)
PUBLICATION_CLAIM_BOUNDARY = (
"This receipt records separately verified publication evidence. Validation "
"does not mutate the repository, adopt source state, deploy, or clear a hold; "
"hold state is derived from the separately supplied published source receipt, "
"and Git, the deployment URL, and external receipt IDs are not authenticated."
)
ROLLBACK_CLAIM_BOUNDARY = (
"This receipt records separately verified rollback evidence. Validation does "
"not run or authenticate Git, inspect the live deployment, deploy, restore "
"data, authenticate external receipt IDs, or change source-review holds."
)
APPROVAL_EFFECTS: Mapping[str, bool] = MappingProxyType(
{
"decision_ledger_clears_source_hold": False,
"decision_ledger_publishes": False,
"validator_authenticates_external_evidence": False,
"receipt_clears_source_hold": False,
"receipt_publishes": False,
}
)
PUBLICATION_EFFECTS: Mapping[str, bool] = MappingProxyType(
{
"validator_adopts_source_state": False,
"validator_authenticates_external_evidence": False,
"validator_clears_source_hold": False,
"validator_deploys": False,
"validator_mutates_repository": False,
}
)
ROLLBACK_EFFECTS: Mapping[str, bool] = MappingProxyType(
{
"validator_authenticates_external_evidence": False,
"validator_deploys": False,
"validator_mutates_repository": False,
"validator_restores_data": False,
}
)
TEMPLATE_FINGERPRINTS_V1: Mapping[str, str] = MappingProxyType(
{
"approval": "sha256:7c17aa6ddb7969b4023f8ea9ee4a48f6c4172ae46a2cd1735fff7951d006b365",
"publication": "sha256:73b41f1c37d2572b2e048af3f4c6d6013025a49d4f18d9409701e0e5a26621bd",
"rollback": "sha256:125dd8dcbf6e5cc9333ad48cdc2436981a52a13b571eaac5e5535542c07d2e7c",
}
)
_IDENTIFIER = re.compile(r"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$")
_OWNER_CODE = re.compile(r"^[A-Z][A-Z0-9_-]{1,15}$")
_FINGERPRINT = re.compile(r"^sha256:[0-9a-f]{64}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
_INVALID_PERCENT_ESCAPE = re.compile(r"%(?![0-9A-Fa-f]{2})")
_PLACEHOLDER_IDENTIFIERS = {
"na",
"none",
"notapplicable",
"not-run",
"not_run",
"notrun",
"pending",
"placeholder",
"tbd",
"todo",
"unassigned",
"unknown",
}
def _fingerprint(payload: object) -> str:
encoded = json.dumps(
payload,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
return "sha256:" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()
def _exact_keys(value: Any, expected: set[str], field: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
unknown = sorted(set(value) - expected)
missing = sorted(expected - set(value))
if unknown:
raise ValueError(f"{field}: unknown fields: {', '.join(unknown)}")
if missing:
raise ValueError(f"{field}: missing fields: {', '.join(missing)}")
return value
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise ValueError(f"duplicate JSON field {key!r}")
result[key] = value
return result
def _reject_nonfinite_constant(value: str) -> None:
raise ValueError(f"receipt uses non-finite JSON value {value}")
def _load_json(path: Path) -> dict[str, Any]:
descriptor = -1
try:
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
descriptor = os.open(path, flags)
metadata = os.fstat(descriptor)
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(f"{path}: receipt input must be a regular file")
if metadata.st_size > MAX_RECEIPT_BYTES:
raise ValueError(
f"{path}: receipt exceeds the {MAX_RECEIPT_BYTES}-byte limit"
)
with os.fdopen(descriptor, "rb", closefd=True) as source:
descriptor = -1
raw_bytes = source.read(MAX_RECEIPT_BYTES + 1)
except ValueError:
raise
except OSError as error:
raise ValueError(f"{path}: receipt could not be loaded") from error
finally:
if descriptor >= 0:
os.close(descriptor)
if len(raw_bytes) > MAX_RECEIPT_BYTES:
raise ValueError(f"{path}: receipt exceeds the {MAX_RECEIPT_BYTES}-byte limit")
try:
encoded = raw_bytes.decode("utf-8")
except UnicodeDecodeError as error:
raise ValueError(f"{path}: receipt is not valid UTF-8") from error
try:
raw = json.loads(
encoded,
object_pairs_hook=_unique_object,
parse_constant=_reject_nonfinite_constant,
)
except (json.JSONDecodeError, RecursionError) as error:
raise ValueError(f"{path}: receipt could not be loaded") from error
if not isinstance(raw, dict):
raise ValueError(f"{path}: expected a JSON object")
return raw
def _identifier(value: Any, field: str) -> str:
if not isinstance(value, str) or not _IDENTIFIER.fullmatch(value):
raise ValueError(f"{field}: expected a stable identifier")
return value
def _optional_identifier(value: Any, field: str) -> str | None:
if value is None:
return None
return _identifier(value, field)
def _evidence_identifier(value: Any, field: str) -> str:
identifier = _identifier(value, field)
if _contains_placeholder(identifier):
raise ValueError(f"{field}: placeholder evidence identifiers are not allowed")
return identifier
def _contains_placeholder(value: str) -> bool:
normalized = re.sub(r"[-_.]", "", value.lower())
tokens = {token for token in re.split(r"[-_.]", value.lower()) if token}
return normalized in _PLACEHOLDER_IDENTIFIERS or bool(
tokens & _PLACEHOLDER_IDENTIFIERS
)
def _optional_evidence_identifier(value: Any, field: str) -> str | None:
if value is None:
return None
return _evidence_identifier(value, field)
def _optional_fingerprint(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not _FINGERPRINT.fullmatch(value):
raise ValueError(f"{field}: expected a SHA-256 fingerprint or null")
return value
def _choice(value: Any, allowed: tuple[str, ...], field: str) -> str:
if not isinstance(value, str) or value not in allowed:
raise ValueError(f"{field}: expected one of {', '.join(allowed)}")
return value
def _optional_choice(value: Any, allowed: tuple[str, ...], field: str) -> str | None:
if value is None:
return None
return _choice(value, allowed, field)
def _owner_code(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not _OWNER_CODE.fullmatch(value):
raise ValueError(f"{field}: expected an opaque uppercase owner code or null")
if _contains_placeholder(value):
raise ValueError(f"{field}: placeholder owner codes are not allowed")
return value
def _validation_now(value: datetime | None) -> datetime:
now = value or datetime.now(UTC)
if now.tzinfo is None or now.utcoffset() != timedelta(0):
raise ValueError("validation time must be timezone-aware UTC")
return now.astimezone(UTC)
def _timestamp(
value: Any,
field: str,
*,
now: datetime,
) -> datetime | None:
if value is None:
return None
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError(f"{field}: expected a whole-second UTC timestamp or null")
try:
parsed = datetime.fromisoformat(value[:-1] + "+00:00")
except ValueError as error:
raise ValueError(f"{field}: invalid UTC timestamp") from error
if parsed.tzinfo != UTC or parsed.microsecond or _timestamp_text(parsed) != value:
raise ValueError(f"{field}: expected a whole-second UTC timestamp")
if parsed > now:
raise ValueError(f"{field}: future timestamps are not allowed")
return parsed
def _timestamp_text(parsed: datetime | None) -> str | None:
return parsed.strftime("%Y-%m-%dT%H:%M:%SZ") if parsed is not None else None
def _https_url(value: Any, field: str) -> str | None:
if value is None:
return None
if (
not isinstance(value, str)
or not value
or value != value.strip()
or any(character.isspace() or ord(character) < 0x20 for character in value)
or "\x7f" in value
or "\\" in value
or _INVALID_PERCENT_ESCAPE.search(value)
):
raise ValueError(f"{field}: expected an HTTPS URL or null")
try:
parsed = urlsplit(value)
_ = parsed.port
except ValueError as error:
raise ValueError(f"{field}: expected an HTTPS URL or null") from error
if (
parsed.scheme != "https"
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
or parsed.fragment
or parsed.hostname != parsed.hostname.strip(".")
or ".." in parsed.hostname
):
raise ValueError(
f"{field}: expected an HTTPS URL without credentials or fragment"
)
return value
def _optional_commit(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not _COMMIT_SHA.fullmatch(value):
raise ValueError(f"{field}: expected a full lowercase commit SHA or null")
return value
def _receipt_ids(value: Any, field: str) -> tuple[str, ...] | None:
if value is None:
return None
if not isinstance(value, list) or not value:
raise ValueError(f"{field}: expected a non-empty list or null")
result = tuple(
_evidence_identifier(item, f"{field}[{index}]")
for index, item in enumerate(value)
)
if list(result) != sorted(result) or len(result) != len(set(result)):
raise ValueError(f"{field}: expected sorted unique receipt IDs")
return result
def _source_resolutions(value: Any) -> tuple[SourceResolution, ...] | None:
if value is None:
return None
if not isinstance(value, list) or not value:
raise ValueError(
"decision.source_resolutions: expected a non-empty list or null"
)
resolutions: list[SourceResolution] = []
for index, item in enumerate(value):
field = f"decision.source_resolutions[{index}]"
raw = _exact_keys(
item,
{
"source_id",
"source_record_fingerprint",
"resolution",
"target_sha256",
},
field,
)
source_id = _identifier(raw["source_id"], f"{field}.source_id")
fingerprint = _optional_fingerprint(
raw["source_record_fingerprint"],
f"{field}.source_record_fingerprint",
)
if fingerprint is None:
raise ValueError(f"{field}.source_record_fingerprint: value is required")
resolution = _choice(
raw["resolution"], SOURCE_RESOLUTIONS, f"{field}.resolution"
)
target = raw["target_sha256"]
if target is not None and (
not isinstance(target, str) or not _SHA256.fullmatch(target)
):
raise ValueError(f"{field}.target_sha256: expected SHA-256 or null")
if (resolution == "retain_hold") != (target is None):
raise ValueError(
f"{field}: retain_hold requires a null target; other resolutions "
"require an exact target digest"
)
resolutions.append(SourceResolution(source_id, fingerprint, resolution, target))
source_ids = [item.source_id for item in resolutions]
if source_ids != sorted(source_ids) or len(source_ids) != len(set(source_ids)):
raise ValueError(
"decision.source_resolutions: expected one sorted record per source"
)
return tuple(resolutions)
def _validate_source_resolution_context(
resolutions: tuple[SourceResolution, ...],
context: ReleaseContext,
) -> None:
changed = {source.source_id: source for source in context.worklist.changed_sources}
source_items = {
item.target_id: item
for item in context.worklist.items
if item.item_type == "source_reverification"
}
if [item.source_id for item in resolutions] != sorted(changed):
raise ValueError(
"decision.source_resolutions must cover every changed source exactly once"
)
for resolution in resolutions:
source = changed[resolution.source_id]
if (
resolution.source_id not in source_items
or resolution.source_record_fingerprint
!= source_items[resolution.source_id].target_fingerprint
):
raise ValueError(
"decision.source_resolutions source record fingerprint does not match"
)
expected = {
"adopt_observed": source.observed_sha256,
"restore_recorded": source.recorded_sha256,
"retain_hold": None,
}[resolution.resolution]
if resolution.target_sha256 != expected:
raise ValueError(
"decision.source_resolutions target digest does not match its "
"explicit resolution"
)
@dataclass(frozen=True)
class ReleaseBinding:
source_snapshot_id: str | None
source_snapshot_fingerprint: str | None
worklist_id: str | None
worklist_fingerprint: str | None
decision_ledger_fingerprint: str | None
def to_dict(self) -> dict[str, str | None]:
return {
"source_snapshot_id": self.source_snapshot_id,
"source_snapshot_fingerprint": self.source_snapshot_fingerprint,
"worklist_id": self.worklist_id,
"worklist_fingerprint": self.worklist_fingerprint,
"decision_ledger_fingerprint": self.decision_ledger_fingerprint,
}
def is_empty(self) -> bool:
return all(value is None for value in self.to_dict().values())
def is_complete(self) -> bool:
return all(value is not None for value in self.to_dict().values())
@dataclass(frozen=True)
class ReceiptReference:
receipt_id: str | None
receipt_fingerprint: str | None
def to_dict(self) -> dict[str, str | None]:
return {
"receipt_id": self.receipt_id,
"receipt_fingerprint": self.receipt_fingerprint,
}
def is_empty(self) -> bool:
return self.receipt_id is None and self.receipt_fingerprint is None
def is_complete(self) -> bool:
return self.receipt_id is not None and self.receipt_fingerprint is not None
@dataclass(frozen=True)
class ReleaseContext:
snapshot: SourceStateSnapshot
worklist: ReviewWorklist
decisions: ReviewDecisionLedger
binding: ReleaseBinding
sources_path: Path
rules_path: Path
golden_path: Path
readiness_contexts: tuple[ReadinessReviewContext, ...]
as_of: date | None
input_fingerprints: tuple[str, str, str]
@dataclass(frozen=True)
class SourceResolution:
source_id: str
source_record_fingerprint: str
resolution: str
target_sha256: str | None
def to_dict(self) -> dict[str, str | None]:
return {
"source_id": self.source_id,
"source_record_fingerprint": self.source_record_fingerprint,
"resolution": self.resolution,
"target_sha256": self.target_sha256,
}
@dataclass(frozen=True)
class ApprovalReceipt:
receipt_id: str
status: str
binding: ReleaseBinding
outcome: str | None
reviewer_code: str | None
authority_receipt_id: str | None
decided_at: str | None
evidence_receipt_ids: tuple[str, ...] | None
source_resolutions: tuple[SourceResolution, ...] | None
def to_dict(self) -> dict[str, object]:
return {
"schema_version": RECEIPT_SCHEMA_VERSION,
"receipt_type": "source_change_approval",
"receipt_id": self.receipt_id,
"status": self.status,
"claim_boundary": APPROVAL_CLAIM_BOUNDARY,
"release_binding": self.binding.to_dict(),
"decision": {
"outcome": self.outcome,
"reviewer_code": self.reviewer_code,
"authority_receipt_id": self.authority_receipt_id,
"decided_at": self.decided_at,
"evidence_receipt_ids": (
list(self.evidence_receipt_ids)
if self.evidence_receipt_ids is not None
else None
),
"source_resolutions": (
[resolution.to_dict() for resolution in self.source_resolutions]
if self.source_resolutions is not None
else None
),
},
"effects": dict(APPROVAL_EFFECTS),
}
def fingerprint(self) -> str:
return _fingerprint(self.to_dict())
@dataclass(frozen=True)
class PublicationReceipt:
receipt_id: str
status: str
binding: ReleaseBinding
approval: ReceiptReference
actor_code: str | None
started_at: str | None
completed_at: str | None
baseline_commit_sha: str | None
published_commit_sha: str | None
published_url: str | None
published_source_snapshot_id: str | None
published_source_snapshot_fingerprint: str | None
hold_state: str | None
verification_receipt_id: str | None
def to_dict(self) -> dict[str, object]:
return {
"schema_version": RECEIPT_SCHEMA_VERSION,
"receipt_type": "source_change_publication",
"receipt_id": self.receipt_id,
"status": self.status,
"claim_boundary": PUBLICATION_CLAIM_BOUNDARY,
"release_binding": self.binding.to_dict(),
"approval_receipt": self.approval.to_dict(),
"publication": {
"actor_code": self.actor_code,
"started_at": self.started_at,
"completed_at": self.completed_at,
"baseline_commit_sha": self.baseline_commit_sha,
"published_commit_sha": self.published_commit_sha,
"published_url": self.published_url,
"published_source_snapshot_id": self.published_source_snapshot_id,
"published_source_snapshot_fingerprint": (
self.published_source_snapshot_fingerprint
),
"hold_state": self.hold_state,
"verification_receipt_id": self.verification_receipt_id,
},
"effects": dict(PUBLICATION_EFFECTS),
}
def fingerprint(self) -> str:
return _fingerprint(self.to_dict())
@dataclass(frozen=True)
class RollbackReceipt:
receipt_id: str
status: str
binding: ReleaseBinding
publication: ReceiptReference
actor_code: str | None
triggered_at: str | None
completed_at: str | None
reason: str | None
restored_commit_sha: str | None
restored_url: str | None
restored_source_snapshot_id: str | None
restored_source_snapshot_fingerprint: str | None
hold_state: str | None
verification_receipt_id: str | None
def to_dict(self) -> dict[str, object]:
return {
"schema_version": RECEIPT_SCHEMA_VERSION,
"receipt_type": "source_change_rollback",
"receipt_id": self.receipt_id,
"status": self.status,
"claim_boundary": ROLLBACK_CLAIM_BOUNDARY,
"release_binding": self.binding.to_dict(),
"publication_receipt": self.publication.to_dict(),
"rollback": {
"actor_code": self.actor_code,
"triggered_at": self.triggered_at,
"completed_at": self.completed_at,
"reason": self.reason,
"restored_commit_sha": self.restored_commit_sha,
"restored_url": self.restored_url,
"restored_source_snapshot_id": self.restored_source_snapshot_id,
"restored_source_snapshot_fingerprint": (
self.restored_source_snapshot_fingerprint
),
"hold_state": self.hold_state,
"verification_receipt_id": self.verification_receipt_id,
},
"effects": dict(ROLLBACK_EFFECTS),
}
def fingerprint(self) -> str:
return _fingerprint(self.to_dict())
def build_release_context(
snapshot: SourceStateSnapshot,
worklist: ReviewWorklist,
decisions: ReviewDecisionLedger,
*,
sources_path: Path,
rules_path: Path,
golden_path: Path,
readiness_contexts: tuple[ReadinessReviewContext, ...] = (),
as_of: date | None = None,
) -> ReleaseContext:
"""Re-derive and bind exact artifacts without interpreting publication."""
canonical_sources_path = _canonical_input_path(sources_path, "sources_path")
canonical_rules_path = _canonical_input_path(rules_path, "rules_path")
canonical_golden_path = _canonical_input_path(golden_path, "golden_path")
input_fingerprints = _input_fingerprints(
canonical_sources_path,
canonical_rules_path,
canonical_golden_path,
)
canonical_snapshot = validate_source_state_snapshot(
snapshot,
canonical_sources_path,
canonical_rules_path,
canonical_golden_path,
)
sources = load_sources(canonical_sources_path, today=as_of)
rules = load_rules(canonical_rules_path, today=as_of)
golden_cases = load_golden(canonical_golden_path, rules)
canonical_worklist = build_review_worklist(
canonical_snapshot,
sources,
rules,
golden_cases,
readiness_contexts=readiness_contexts,
)
if worklist.to_dict() != canonical_worklist.to_dict():
raise ValueError("worklist does not match the canonical affected-output set")
if input_fingerprints != _input_fingerprints(
canonical_sources_path,
canonical_rules_path,
canonical_golden_path,
):
raise ValueError("source, rule, or Golden input changed during validation")
return _context_from_artifacts(
canonical_snapshot,
worklist,
decisions,
sources_path=canonical_sources_path,
rules_path=canonical_rules_path,
golden_path=canonical_golden_path,
readiness_contexts=readiness_contexts,
as_of=as_of,
input_fingerprints=input_fingerprints,
)
def _canonical_input_path(path: Path, field: str) -> Path:
if not isinstance(path, Path):
raise ValueError(f"{field}: expected a filesystem path")
try:
return path.resolve(strict=True)
except OSError as error:
raise ValueError(f"{field}: input does not exist") from error
def _raw_input_fingerprint(path: Path) -> str:
"""Fingerprint the exact loader-visible bytes around context derivation."""
if path.is_dir():
files = sorted(
item for item in path.glob("*.json") if item.name != "index.json"
)
if not files:
raise ValueError(f"{path}: no input files found")
else:
files = [path]
digest = hashlib.sha256()
for item in files:
try:
relative = item.relative_to(path) if path.is_dir() else Path(item.name)
raw = item.read_bytes()
except OSError as error:
raise ValueError(f"{item}: input could not be fingerprinted") from error
digest.update(relative.as_posix().encode("utf-8"))
digest.update(b"\0")
digest.update(len(raw).to_bytes(8, "big"))
digest.update(raw)
return "sha256:" + digest.hexdigest()
def _input_fingerprints(
sources_path: Path,
rules_path: Path,
golden_path: Path,
) -> tuple[str, str, str]:
return (
_raw_input_fingerprint(sources_path),
_raw_input_fingerprint(rules_path),
_raw_input_fingerprint(golden_path),
)
def _context_from_artifacts(
snapshot: SourceStateSnapshot,
worklist: ReviewWorklist,
decisions: ReviewDecisionLedger,
*,
sources_path: Path,
rules_path: Path,
golden_path: Path,
readiness_contexts: tuple[ReadinessReviewContext, ...],
as_of: date | None,
input_fingerprints: tuple[str, str, str],
) -> ReleaseContext:
"""Recheck bindings for an already canonically derived in-process context."""
snapshot_fingerprint = source_state_fingerprint(snapshot)
_validate_worklist_context(snapshot, snapshot_fingerprint, worklist)
_validate_decision_context(worklist, decisions)
binding = ReleaseBinding(
source_snapshot_id=snapshot.snapshot_id,
source_snapshot_fingerprint=snapshot_fingerprint,
worklist_id=worklist.worklist_id,
worklist_fingerprint=worklist.fingerprint(),
decision_ledger_fingerprint=decisions.fingerprint(),
)
return ReleaseContext(
snapshot,
worklist,
decisions,
binding,
sources_path,
rules_path,
golden_path,
readiness_contexts,
as_of,
input_fingerprints,
)
def _validate_worklist_context(
snapshot: SourceStateSnapshot,
snapshot_fingerprint: str,
worklist: ReviewWorklist,
) -> None:
if worklist.source_snapshot_id != snapshot.snapshot_id:
raise ValueError("worklist source snapshot ID does not match")
if worklist.source_snapshot_fingerprint != snapshot_fingerprint:
raise ValueError("worklist source snapshot fingerprint does not match")
if worklist.receipt_status != snapshot.receipt.status:
raise ValueError("worklist source receipt status does not match")
if worklist.changed_source_ids != snapshot.changed_source_ids:
raise ValueError("worklist changed-source IDs do not match")
if worklist.status != "open" or not snapshot.changed_source_ids:
raise ValueError("source release requires an open changed-source worklist")
def _validate_decision_context(
worklist: ReviewWorklist,
decisions: ReviewDecisionLedger,
) -> None:
if decisions.worklist_id != worklist.worklist_id:
raise ValueError("decision ledger worklist ID does not match")
if decisions.worklist_fingerprint != worklist.fingerprint():
raise ValueError("decision ledger worklist fingerprint does not match")
items = worklist.item_map()
decision_ids = [entry.item_id for entry in decisions.entries]
if decision_ids != sorted(items) or len(decision_ids) != len(set(decision_ids)):
raise ValueError("decision ledger must cover every work item exactly once")
for entry in decisions.entries:
if entry.item_fingerprint != items[entry.item_id].fingerprint():
raise ValueError("decision ledger item fingerprint does not match")
_validate_context_decision(entry)
def _validate_context_decision(entry: ReviewDecision) -> None:
if entry.status not in DECISION_STATUSES:
raise ValueError("decision ledger contains an invalid status")
if entry.owner_code is not None:
_owner_code(entry.owner_code, "decision ledger owner code")
if entry.assignee_role is not None and not _IDENTIFIER.fullmatch(
entry.assignee_role
):
raise ValueError("decision ledger contains an invalid assignee role identifier")
if entry.disposition is not None and entry.disposition not in DECISION_DISPOSITIONS:
raise ValueError("decision ledger contains an invalid disposition")
if entry.evidence_receipt_id is not None:
_evidence_identifier(
entry.evidence_receipt_id, "decision ledger evidence receipt ID"
)
assigned = _ledger_date(entry.assigned_on, "assigned_on")
due = _ledger_date(entry.due_on, "due_on")
decided = _ledger_date(entry.decided_on, "decided_on")
values = (
entry.owner_code,
entry.assigned_on,
entry.assignee_role,
entry.due_on,
entry.disposition,
entry.decided_on,
entry.evidence_receipt_id,
)
if entry.status == "unassigned" and any(values):
raise ValueError("unassigned decision ledger entry carries metadata")
if entry.status == "assigned" and (
entry.owner_code is None
or assigned is None
or entry.assignee_role is None
or due is None
or any(values[4:])
or (assigned is not None and due is not None and due < assigned)
):
raise ValueError("assigned decision ledger entry has invalid metadata")
if entry.status == "resolved" and (
not all(values)
or assigned is None
or decided is None
or decided < assigned
or (due is not None and assigned is not None and due < assigned)
):
raise ValueError("resolved decision ledger entry has invalid metadata")
def _ledger_date(value: str | None, field: str) -> date | None:
if value is None:
return None
if not isinstance(value, str):
raise ValueError(f"decision ledger contains an invalid {field} date")
try:
parsed = date.fromisoformat(value)
except ValueError as error:
raise ValueError(f"decision ledger contains an invalid {field} date") from error
if parsed.isoformat() != value:
raise ValueError(f"decision ledger contains an invalid {field} date")
return parsed
def _empty_binding() -> ReleaseBinding:
return ReleaseBinding(None, None, None, None, None)
def approval_template(
receipt_id: str = "source-change-approval-template",
) -> ApprovalReceipt:
return ApprovalReceipt(
receipt_id=_identifier(receipt_id, "receipt_id"),
status="not_run",
binding=_empty_binding(),
outcome=None,
reviewer_code=None,
authority_receipt_id=None,
decided_at=None,
evidence_receipt_ids=None,
source_resolutions=None,
)
def publication_template(
receipt_id: str = "source-change-publication-template",
) -> PublicationReceipt:
return PublicationReceipt(
receipt_id=_identifier(receipt_id, "receipt_id"),
status="not_run",
binding=_empty_binding(),
approval=ReceiptReference(None, None),
actor_code=None,
started_at=None,
completed_at=None,
baseline_commit_sha=None,
published_commit_sha=None,
published_url=None,
published_source_snapshot_id=None,
published_source_snapshot_fingerprint=None,
hold_state=None,
verification_receipt_id=None,
)
def rollback_template(
receipt_id: str = "source-change-rollback-template",
) -> RollbackReceipt:
return RollbackReceipt(
receipt_id=_identifier(receipt_id, "receipt_id"),
status="not_run",
binding=_empty_binding(),
publication=ReceiptReference(None, None),
actor_code=None,
triggered_at=None,
completed_at=None,
reason=None,
restored_commit_sha=None,
restored_url=None,
restored_source_snapshot_id=None,
restored_source_snapshot_fingerprint=None,
hold_state=None,
verification_receipt_id=None,
)
def prepared_receipts(
release_id: str,
context: ReleaseContext,
) -> tuple[ApprovalReceipt, PublicationReceipt, RollbackReceipt]:
"""Create bound ``not_run`` receipts without creating an approval claim."""
context = _validated_context(context)
stable_id = _evidence_identifier(release_id, "release_id")
approval = approval_template(f"{stable_id}-approval")
approval = ApprovalReceipt(
receipt_id=approval.receipt_id,
status=approval.status,
binding=context.binding,
outcome=None,
reviewer_code=None,
authority_receipt_id=None,
decided_at=None,
evidence_receipt_ids=None,
source_resolutions=None,
)
publication = publication_template(f"{stable_id}-publication")
publication = PublicationReceipt(
receipt_id=publication.receipt_id,
status=publication.status,
binding=context.binding,
approval=ReceiptReference(approval.receipt_id, approval.fingerprint()),
actor_code=None,
started_at=None,
completed_at=None,
baseline_commit_sha=None,
published_commit_sha=None,
published_url=None,
published_source_snapshot_id=None,
published_source_snapshot_fingerprint=None,
hold_state=None,
verification_receipt_id=None,
)
rollback = rollback_template(f"{stable_id}-rollback")
rollback = RollbackReceipt(
receipt_id=rollback.receipt_id,
status=rollback.status,
binding=context.binding,
publication=ReceiptReference(publication.receipt_id, publication.fingerprint()),