Repository navigation
Expand file tree
/
Copy pathbuild_timed_86400_flowes_x3x3.py
More file actions
1703 lines (1542 loc) · 63.6 KB
/
Copy pathbuild_timed_86400_flowes_x3x3.py
File metadata and controls
1703 lines (1542 loc) · 63.6 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
"""Build or watch the additive folder-Calming-OIL FLOWes X3 X3 V2 bundle.
The production watch credits only elapsed ``time.monotonic_ns()`` within a live
session. A restart resumes from the last sealed checkpoint; wall-clock gaps and
uncheckpointed seconds receive no credit. ``--fake-clock-build`` is a deterministic
CI fixture and is explicitly tagged as non-measured timing.
This program is a static public descriptor builder. It performs no network access,
grants no execution authority, and emits no physical light or energy.
"""
from __future__ import annotations
import argparse
import hashlib
import math
import os
import re
import struct
import sys
import tempfile
import time
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterable, Protocol, Sequence
from urllib.parse import quote
SCHEMA = "ASOLARIA-TIMED-86400-FOLDER-CALMING-OILS-FLOWes-X3-X3-V2"
SOURCE_SCHEMA = "ASOLARIA-PUBLIC-FOLDER-CALMING-OILS-RUST-181-V1"
TARGET_SECONDS = 86_400
SOURCE_HBP = "PUBLIC-FOLDER-CALMING-OILS.hbp"
SOURCE_HBI = "PUBLIC-FOLDER-CALMING-OILS.hbi"
COMMITTED_SOURCE_HBP_SHA256 = (
"43300780cac2b85e3ed6cfa10398052f530ccbf76c43b404e650c26c9ed8b006"
)
COMMITTED_SOURCE_HBI_SHA256 = (
"9920d5cb2031d6453fba2d410e4b2f6e0136a4537fa6ea2ea9385c163503a28b"
)
BASE = "TIMED-86400-FOLDER-CALMING-OILS-FLOWes-X3-X3-V2"
OUTPUT_HBP = BASE + ".hbp"
OUTPUT_HBI = BASE + ".hbi"
OUTPUT_SVG = BASE + ".svg"
OUTPUT_GGUF = BASE + ".gguf"
OUTPUT_STDOUT = BASE + "-STDOUT.hbp"
OUTPUT_JOURNAL = BASE + "-JOURNAL.hbp"
OUTPUT_NAMES = (
OUTPUT_HBP,
OUTPUT_HBI,
OUTPUT_SVG,
OUTPUT_GGUF,
OUTPUT_STDOUT,
OUTPUT_JOURNAL,
)
FAMILIES = ("BROWN", "ANTI_BROWN", "ANTI_ANTI_BROWN")
DIRECTIONS = ("NEGATIVE", "CENTRE", "POSITIVE")
CENTER_MEMBERS = ("HBI", "HBP", "SHA", "SH", "HASH")
CENTER_TRAVERSAL = "HBI->HBP->SH->HASH->SHA"
COMMITMENT_LABELS = CENTER_MEMBERS
OBSERVATION_LIMIT = 60
GGUF_MAGIC = 0x46554747
GGUF_VERSION = 3
GGUF_TYPE_UINT32 = 4
GGUF_TYPE_STRING = 8
GGUF_TYPE_UINT64 = 10
GGML_TYPE_I8 = 24
GGUF_ALIGNMENT = 32
DESCRIPTOR_WIDTH = 64
SHA256_RE = re.compile(r"[0-9a-f]{64}")
class FlowesError(ValueError):
"""A closed-bundle or journal invariant failed."""
@dataclass(frozen=True)
class SourceLeaf:
index: int
folder_i: int
family_i: int
family: str
source_level: int
repo_id: str
folder_id: str
leaf_id: str
tree_commitment: str
object_sha256: str
view_x: int
view_y: int
view_z: int
projected_u: int
projected_v: int
color: str
hbi: str
hbp: str
sh: str
hash_value: str
sha: str
@dataclass(frozen=True)
class SourceBundle:
hbp: bytes
hbi: bytes
hbp_sha256: str
hbi_sha256: str
folder_count: int
leaves: tuple[SourceLeaf, ...]
@dataclass(frozen=True)
class Session:
index: int
baseline_seconds: int
@dataclass(frozen=True)
class Checkpoint:
index: int
checkpoint_seconds: int
session_i: int
session_credited_seconds: int
previous_hash: str
checkpoint_hash: str
@dataclass(frozen=True)
class Journal:
target_seconds: int
timing_mode: str
source_hbp_sha256: str
source_hbi_sha256: str
sessions: tuple[Session, ...]
checkpoints: tuple[Checkpoint, ...]
@property
def accumulated_seconds(self) -> int:
return self.checkpoints[-1].checkpoint_seconds if self.checkpoints else 0
@property
def complete(self) -> bool:
return self.accumulated_seconds == self.target_seconds
@dataclass(frozen=True)
class Ring:
index: int
level: int
checkpoint_seconds: int
family_i: int
family: str
direction_i: int
direction: str
window_start: int
observed_rows: int
reflect_2d_hash: str
collect_3d_hash: str
signed_2d_hash: str
previous_ring_hash: str
ring_hash: str
@dataclass(frozen=True)
class Cell:
index: int
source: SourceLeaf
direction_i: int
direction: str
flowe_id: str
commitments: tuple[str, str, str, str, str]
class Clock(Protocol):
def monotonic_ns(self) -> int: ...
def sleep(self, seconds: float) -> None: ...
class SystemClock:
def monotonic_ns(self) -> int:
return time.monotonic_ns()
def sleep(self, seconds: float) -> None:
time.sleep(seconds)
class WriterLock:
"""Nonblocking OS-held lock keyed to one resolved output directory.
The lock file lives in the platform temporary directory so normal builds do
not leave repository artifacts. Its tuple bytes are diagnostic only; the OS
advisory lock is the authority and is released automatically on process death.
"""
def __init__(self, output_dir: Path, mode: str):
self.output_dir = output_dir.resolve()
self.output_identity = os.path.normcase(
os.path.realpath(str(self.output_dir))
)
self.mode = mode
self.path: Path | None = None
self.fd: int | None = None
self._windows = os.name == "nt"
def __enter__(self) -> "WriterLock":
lock_root = Path(tempfile.gettempdir()) / "asolaria-flowes-writer-locks"
lock_root.mkdir(parents=True, exist_ok=True)
key = sha256_bytes(self.output_identity.encode("utf-8"))
self.path = lock_root / (key + ".lock")
fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o600)
try:
if self._windows:
import msvcrt
if os.fstat(fd).st_size < 1:
os.write(fd, b"\0")
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, OSError) as exc:
os.close(fd)
raise FlowesError("WRITER_LOCK_ACTIVE") from exc
self.fd = fd
metadata = (
tuple_row(
"FLOWEX9WRITERLOCK", schema=SCHEMA, pid=os.getpid(), mode=self.mode,
output_dir_sha256=key, os_advisory_lock=1,
lock_bytes_authority=0, json=0,
)
+ "\n"
).encode("utf-8")
os.lseek(fd, 0, os.SEEK_SET)
os.ftruncate(fd, 0)
os.write(fd, metadata)
os.fsync(fd)
return self
def assert_held(self, output_dir: Path) -> None:
candidate_identity = os.path.normcase(
os.path.realpath(str(output_dir.resolve()))
)
if self.fd is None or candidate_identity != self.output_identity:
raise FlowesError("WRITER_LOCK_REQUIRED")
def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
if self.fd is None:
return
fd = self.fd
self.fd = None
try:
os.lseek(fd, 0, os.SEEK_SET)
if self._windows:
import msvcrt
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def domain_hash(domain: str, *parts: object) -> str:
digest = hashlib.sha256()
domain_bytes = domain.encode("utf-8")
digest.update(len(domain_bytes).to_bytes(8, "big"))
digest.update(domain_bytes)
for part in parts:
raw = part if isinstance(part, bytes) else str(part).encode("utf-8")
digest.update(len(raw).to_bytes(8, "big"))
digest.update(raw)
return digest.hexdigest()
def encode_value(value: object) -> str:
return quote(str(value), safe="._,-")
def tuple_row(tag: str, **fields: object) -> str:
return tag + "|" + "|".join(
f"{key}={encode_value(value)}" for key, value in fields.items()
)
def parse_tuple(line: str, expected_tag: str | None = None) -> dict[str, str]:
parts = line.split("|")
if not parts or not parts[0]:
raise FlowesError("TUPLE_TAG")
if expected_tag is not None and parts[0] != expected_tag:
raise FlowesError(f"TUPLE_TAG:{parts[0]}:{expected_tag}")
fields: dict[str, str] = {}
for part in parts[1:]:
if "=" not in part:
raise FlowesError("TUPLE_FIELD")
key, value = part.split("=", 1)
if not key or key in fields:
raise FlowesError("TUPLE_DUPLICATE")
fields[key] = value
return fields
def require_fields(
fields: dict[str, str], expected: dict[str, str], context: str
) -> None:
for key, value in expected.items():
if fields.get(key) != value:
raise FlowesError(f"{context}:{key}")
def require_hash(value: str, context: str) -> str:
if SHA256_RE.fullmatch(value) is None:
raise FlowesError(f"HASH:{context}")
return value
def sidecar_bytes(name: str, data: bytes) -> bytes:
return f"{sha256_bytes(data)} {name}\n".encode("ascii")
def verify_sidecar(path: Path) -> bytes:
if not path.is_file() or path.is_symlink():
raise FlowesError(f"MISSING_OR_LINK:{path.name}")
data = path.read_bytes()
sidecar = path.with_name(path.name + ".sha256")
if not sidecar.is_file() or sidecar.is_symlink():
raise FlowesError(f"SIDECAR_MISSING_OR_LINK:{path.name}")
raw = sidecar.read_bytes()
if raw != sidecar_bytes(path.name, data):
raise FlowesError(f"SIDECAR_MISMATCH:{path.name}")
return data
def verify_footer(lines: Sequence[str], tag: str) -> None:
footer = parse_tuple(lines[-1], tag)
body = ("\n".join(lines[:-1]) + "\n").encode("utf-8")
require_fields(
footer,
{"body_sha256": sha256_bytes(body), "rows": str(len(lines)), "json": "0"},
tag,
)
def schedule(target_seconds: int) -> tuple[int, ...]:
if target_seconds < 1:
raise FlowesError("TARGET_SECONDS")
values = [1, 2, 3, 4]
value = 8
while value < target_seconds:
values.append(value)
value *= 2
values.append(target_seconds)
return tuple(sorted(set(value for value in values if value <= target_seconds)))
def load_source(directory: Path, *, require_committed: bool = True) -> SourceBundle:
directory = directory.resolve()
if not directory.is_dir() or directory.is_symlink():
raise FlowesError("SOURCE_DIRECTORY")
hbp = verify_sidecar(directory / SOURCE_HBP)
hbi = verify_sidecar(directory / SOURCE_HBI)
if b"\r" in hbp or b"\r" in hbi:
raise FlowesError("SOURCE_CR")
hbp_sha = sha256_bytes(hbp)
hbi_sha = sha256_bytes(hbi)
if require_committed and (
hbp_sha != COMMITTED_SOURCE_HBP_SHA256
or hbi_sha != COMMITTED_SOURCE_HBI_SHA256
):
raise FlowesError("COMMITTED_SOURCE_SHA256")
try:
hbp_lines = hbp.decode("utf-8").splitlines()
hbi_lines = hbi.decode("utf-8").splitlines()
except UnicodeDecodeError as exc:
raise FlowesError("SOURCE_UTF8") from exc
if any(not line.endswith("|json=0") for line in hbp_lines + hbi_lines):
raise FlowesError("SOURCE_JSON0")
verify_footer(hbp_lines, "FOLDEROILFTR")
verify_footer(hbi_lines, "FOLDEROILIDXFTR")
header = parse_tuple(hbp_lines[0], "FOLDEROILRUN")
require_fields(header, {"schema": SOURCE_SCHEMA, "families": "3", "json": "0"}, "SOURCE_HEADER")
folder_count = int(header["folders"])
leaf_count = int(header["leaves"])
if folder_count < 1 or leaf_count != folder_count * len(FAMILIES):
raise FlowesError("SOURCE_POPULATION")
if len(hbp_lines) != leaf_count + 13 or len(hbi_lines) != 9:
raise FlowesError("SOURCE_ROW_COUNT")
index_header = parse_tuple(hbi_lines[0], "FOLDEROILIDX")
require_fields(
index_header,
{
"schema": SOURCE_SCHEMA,
"folders": str(folder_count),
"families": "3",
"leaves": str(leaf_count),
"json": "0",
},
"SOURCE_INDEX",
)
hbp_artifacts = [
parse_tuple(line, "ARTIFACT")
for line in hbi_lines
if line.startswith("ARTIFACT|")
and parse_tuple(line).get("kind") == "HBP"
]
if len(hbp_artifacts) != 1:
raise FlowesError("SOURCE_HBI_HBP_COUNT")
require_fields(
hbp_artifacts[0],
{"file": SOURCE_HBP, "sha256": hbp_sha, "json": "0"},
"SOURCE_HBI_HBP",
)
family_rows = [parse_tuple(line, "FAMILY") for line in hbp_lines if line.startswith("FAMILY|")]
if tuple(row.get("name") for row in family_rows) != FAMILIES:
raise FlowesError("SOURCE_FAMILIES")
leaves: list[SourceLeaf] = []
by_folder: dict[int, list[SourceLeaf]] = {}
for line in hbp_lines:
if not line.startswith("OIL|"):
continue
row = parse_tuple(line, "OIL")
for key in (
"path_bytes_embedded", "media_bytes_embedded", "repository_bytes_embedded",
"credentials", "network", "execution", "physical_energy", "authority", "json",
):
if row.get(key) != "0":
raise FlowesError(f"SOURCE_BOUNDARY:{key}")
family = row["family"]
if family not in FAMILIES:
raise FlowesError("SOURCE_LEAF_FAMILY")
commitments = tuple(
require_hash(row[key], f"SOURCE_{key}") for key in ("hbi", "hbp", "sha", "sh", "hash")
)
if len(set(commitments)) != len(commitments):
raise FlowesError("SOURCE_COMMITMENT_COLLISION")
leaf = SourceLeaf(
index=int(row["i"]), folder_i=int(row["folder_i"]),
family_i=FAMILIES.index(family), family=family,
source_level=int(row["level"]), repo_id=require_hash(row["repo_id"], "repo_id"),
folder_id=require_hash(row["folder_id"], "folder_id"),
leaf_id=require_hash(row["leaf_id"], "leaf_id"),
tree_commitment=require_hash(row["tree_commitment_sha256"], "tree_commitment"),
object_sha256=require_hash(row["object_sha256"], "object_sha256"),
view_x=int(row["view_x"]), view_y=int(row["view_y"]), view_z=int(row["view_z"]),
projected_u=int(row["projected_u"]), projected_v=int(row["projected_v"]),
color=row["color"], hbi=commitments[0], hbp=commitments[1],
sha=commitments[2], sh=commitments[3], hash_value=commitments[4],
)
if leaf.index != len(leaves) or not 0 <= leaf.folder_i < folder_count:
raise FlowesError("SOURCE_LEAF_INDEX")
leaves.append(leaf)
by_folder.setdefault(leaf.folder_i, []).append(leaf)
if len(leaves) != leaf_count or len(by_folder) != folder_count:
raise FlowesError("SOURCE_LEAF_COUNT")
for folder_i in range(folder_count):
group = by_folder.get(folder_i, [])
if tuple(leaf.family for leaf in group) != FAMILIES:
raise FlowesError(f"SOURCE_FOLDER_FAMILIES:{folder_i}")
if len({leaf.folder_id for leaf in group}) != 1:
raise FlowesError(f"SOURCE_FOLDER_ID:{folder_i}")
return SourceBundle(hbp, hbi, hbp_sha, hbi_sha, folder_count, tuple(leaves))
def checkpoint_hash(
source_hbp_sha256: str,
target_seconds: int,
checkpoint_i: int,
seconds: int,
session_i: int,
credited: int,
previous_hash: str,
) -> str:
return domain_hash(
SCHEMA + "|JOURNAL_CHECKPOINT",
source_hbp_sha256, target_seconds, checkpoint_i, seconds,
session_i, credited, previous_hash,
)
def journal_bytes(journal: Journal) -> bytes:
rows = [
tuple_row(
"FLOWEX9JOURNAL",
schema=SCHEMA, target_seconds=journal.target_seconds,
timing_mode=journal.timing_mode, source_hbp_sha256=journal.source_hbp_sha256,
source_hbi_sha256=journal.source_hbi_sha256, sessions=len(journal.sessions),
checkpoint_count=len(journal.checkpoints),
accumulated_seconds=journal.accumulated_seconds,
state="COMPLETE" if journal.complete else "IN_PROGRESS",
network=0, execution=0, authority=0, physical_energy=0, json=0,
)
]
rows.extend(
tuple_row(
"SESSION", i=session.index, baseline_seconds=session.baseline_seconds,
wall_clock_credit=0, cross_process_gap_credit=0, json=0,
)
for session in journal.sessions
)
rows.extend(
tuple_row(
"CHECKPOINT", i=item.index, checkpoint_seconds=item.checkpoint_seconds,
session_i=item.session_i, session_credited_seconds=item.session_credited_seconds,
previous_hash=item.previous_hash, checkpoint_hash=item.checkpoint_hash,
monotonic_session_only=1, json=0,
)
for item in journal.checkpoints
)
rows.append(
tuple_row(
"BOUNDARY", wall_clock=0, supplied_start_time=0, cross_process_gap_credit=0,
uncheckpointed_credit=0, network=0, execution=0, authority=0,
physical_energy=0, json=0,
)
)
body = ("\n".join(rows) + "\n").encode("utf-8")
rows.append(tuple_row("FLOWEX9JOURNALFTR", body_sha256=sha256_bytes(body), rows=len(rows) + 1, json=0))
return ("\n".join(rows) + "\n").encode("utf-8")
def parse_journal_bytes(
data: bytes, source: SourceBundle, target_seconds: int, timing_mode: str
) -> Journal:
if b"\r" in data:
raise FlowesError("JOURNAL_CR")
try:
lines = data.decode("utf-8").splitlines()
except UnicodeDecodeError as exc:
raise FlowesError("JOURNAL_UTF8") from exc
if len(lines) < 3 or any(not line.endswith("|json=0") for line in lines):
raise FlowesError("JOURNAL_JSON0")
verify_footer(lines, "FLOWEX9JOURNALFTR")
header = parse_tuple(lines[0], "FLOWEX9JOURNAL")
require_fields(
header,
{
"schema": SCHEMA, "target_seconds": str(target_seconds),
"timing_mode": timing_mode, "source_hbp_sha256": source.hbp_sha256,
"source_hbi_sha256": source.hbi_sha256, "network": "0",
"execution": "0", "authority": "0", "physical_energy": "0", "json": "0",
},
"JOURNAL_HEADER",
)
session_rows = [parse_tuple(line, "SESSION") for line in lines if line.startswith("SESSION|")]
checkpoint_rows = [
parse_tuple(line, "CHECKPOINT") for line in lines if line.startswith("CHECKPOINT|")
]
sessions: list[Session] = []
for row in session_rows:
session = Session(int(row["i"]), int(row["baseline_seconds"]))
if session.index != len(sessions):
raise FlowesError("JOURNAL_SESSION_INDEX")
if session.baseline_seconds < 0 or session.baseline_seconds > target_seconds:
raise FlowesError("JOURNAL_SESSION_BASELINE")
require_fields(
row,
{"wall_clock_credit": "0", "cross_process_gap_credit": "0", "json": "0"},
"JOURNAL_SESSION",
)
prior_rows = [
item for item in checkpoint_rows if int(item["session_i"]) < session.index
]
expected_baseline = int(prior_rows[-1]["checkpoint_seconds"]) if prior_rows else 0
if session.baseline_seconds != expected_baseline:
raise FlowesError("JOURNAL_SESSION_BASELINE_CHAIN")
sessions.append(session)
if checkpoint_rows and not sessions:
raise FlowesError("JOURNAL_CHECKPOINT_WITHOUT_SESSION")
expected_schedule = schedule(target_seconds)
checkpoints: list[Checkpoint] = []
genesis = domain_hash(SCHEMA + "|JOURNAL_GENESIS", source.hbp_sha256, target_seconds)
previous = genesis
last_seconds = 0
last_session_i = 0
for row in checkpoint_rows:
index = int(row["i"])
seconds = int(row["checkpoint_seconds"])
session_i = int(row["session_i"])
credited = int(row["session_credited_seconds"])
if index != len(checkpoints) or index >= len(expected_schedule):
raise FlowesError("JOURNAL_CHECKPOINT_INDEX")
if seconds != expected_schedule[index] or not 0 <= session_i < len(sessions):
raise FlowesError("JOURNAL_CHECKPOINT_POSITION")
if checkpoints and session_i < last_session_i:
raise FlowesError("JOURNAL_SESSION_ROLLBACK")
session = sessions[session_i]
if session.baseline_seconds > last_seconds:
raise FlowesError("JOURNAL_SESSION_FUTURE_BASELINE")
expected_credited = seconds - session.baseline_seconds
if credited != expected_credited or credited < 0:
raise FlowesError("JOURNAL_CREDIT")
expected_hash = checkpoint_hash(
source.hbp_sha256, target_seconds, index, seconds,
session_i, credited, previous,
)
require_fields(
row,
{
"previous_hash": previous, "checkpoint_hash": expected_hash,
"monotonic_session_only": "1", "json": "0",
},
"JOURNAL_CHECKPOINT",
)
checkpoints.append(
Checkpoint(index, seconds, session_i, credited, previous, expected_hash)
)
previous = expected_hash
last_seconds = seconds
last_session_i = session_i
journal = Journal(
target_seconds, timing_mode, source.hbp_sha256, source.hbi_sha256,
tuple(sessions), tuple(checkpoints),
)
require_fields(
header,
{
"sessions": str(len(sessions)), "checkpoint_count": str(len(checkpoints)),
"accumulated_seconds": str(journal.accumulated_seconds),
"state": "COMPLETE" if journal.complete else "IN_PROGRESS",
},
"JOURNAL_SUMMARY",
)
if journal_bytes(journal) != data:
raise FlowesError("JOURNAL_CANONICAL")
return journal
def atomic_write(path: Path, data: bytes) -> None:
if path.exists() and path.is_symlink():
raise FlowesError(f"OUTPUT_LINK:{path.name}")
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
mode="wb", dir=path.parent, prefix=path.name + ".", delete=False
) as handle:
temporary = Path(handle.name)
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
try:
os.replace(temporary, path)
finally:
if temporary.exists():
temporary.unlink()
def write_sealed(path: Path, data: bytes) -> None:
atomic_write(path, data)
atomic_write(path.with_name(path.name + ".sha256"), sidecar_bytes(path.name, data))
def load_journal(
output_dir: Path, source: SourceBundle, target_seconds: int, timing_mode: str
) -> Journal | None:
path = output_dir.resolve() / OUTPUT_JOURNAL
if not path.exists():
if path.with_name(path.name + ".sha256").exists():
raise FlowesError("ORPHAN_JOURNAL_SIDECAR")
return None
data = verify_sidecar(path)
return parse_journal_bytes(data, source, target_seconds, timing_mode)
def save_journal(output_dir: Path, journal: Journal, writer_lock: WriterLock) -> None:
writer_lock.assert_held(output_dir)
write_sealed(output_dir.resolve() / OUTPUT_JOURNAL, journal_bytes(journal))
def begin_session(journal: Journal) -> Journal:
if journal.complete:
return journal
session = Session(len(journal.sessions), journal.accumulated_seconds)
return Journal(
journal.target_seconds, journal.timing_mode,
journal.source_hbp_sha256, journal.source_hbi_sha256,
journal.sessions + (session,), journal.checkpoints,
)
def append_reached_checkpoints(journal: Journal, available_seconds: int) -> Journal:
if not journal.sessions:
raise FlowesError("NO_ACTIVE_SESSION")
active = journal.sessions[-1]
checkpoints = list(journal.checkpoints)
expected = schedule(journal.target_seconds)
genesis = domain_hash(
SCHEMA + "|JOURNAL_GENESIS", journal.source_hbp_sha256, journal.target_seconds
)
previous = checkpoints[-1].checkpoint_hash if checkpoints else genesis
while len(checkpoints) < len(expected) and expected[len(checkpoints)] <= available_seconds:
index = len(checkpoints)
seconds = expected[index]
credited = seconds - active.baseline_seconds
if credited < 0:
raise FlowesError("NEGATIVE_SESSION_CREDIT")
digest = checkpoint_hash(
journal.source_hbp_sha256, journal.target_seconds, index,
seconds, active.index, credited, previous,
)
checkpoints.append(
Checkpoint(index, seconds, active.index, credited, previous, digest)
)
previous = digest
return Journal(
journal.target_seconds, journal.timing_mode,
journal.source_hbp_sha256, journal.source_hbi_sha256,
journal.sessions, tuple(checkpoints),
)
def fake_complete_journal(source: SourceBundle, target_seconds: int) -> Journal:
journal = Journal(
target_seconds, "DETERMINISTIC_FAKE_CLOCK", source.hbp_sha256,
source.hbi_sha256, (), (),
)
journal = begin_session(journal)
return append_reached_checkpoints(journal, target_seconds)
def _family_leaves(source: SourceBundle) -> tuple[tuple[SourceLeaf, ...], ...]:
groups = tuple(
tuple(leaf for leaf in source.leaves if leaf.family == family)
for family in FAMILIES
)
if any(len(group) != source.folder_count for group in groups):
raise FlowesError("FAMILY_POPULATION")
return groups
def build_rings(source: SourceBundle, checkpoints: Sequence[int]) -> tuple[Ring, ...]:
groups = _family_leaves(source)
previous: dict[tuple[int, int], str] = {
(family_i, direction_i): domain_hash(
SCHEMA + "|RING_GENESIS", source.hbp_sha256, family, direction
)
for family_i, family in enumerate(FAMILIES)
for direction_i, direction in enumerate(DIRECTIONS)
}
rings: list[Ring] = []
for level, checkpoint_seconds in enumerate(checkpoints):
for family_i, family in enumerate(FAMILIES):
group = groups[family_i]
observed_rows = min(OBSERVATION_LIMIT, len(group))
for direction_i, direction in enumerate(DIRECTIONS):
start = (
level * OBSERVATION_LIMIT + direction_i * max(1, OBSERVATION_LIMIT // 3)
) % len(group)
observed = tuple(group[(start + offset) % len(group)] for offset in range(observed_rows))
reflect_2d = domain_hash(
SCHEMA + "|SELF_REFLECT_2D", family, direction, checkpoint_seconds,
*(f"{leaf.projected_u},{leaf.projected_v},{leaf.color},{leaf.leaf_id}" for leaf in observed),
)
collect_3d = domain_hash(
SCHEMA + "|COLLECT_3D", family, direction, checkpoint_seconds,
*(f"{leaf.view_x},{leaf.view_y},{leaf.view_z},{leaf.tree_commitment}" for leaf in observed),
)
signed_2d = domain_hash(
SCHEMA + "|SELF_REDUCE_SIGNED_2D", direction,
reflect_2d, collect_3d,
*(leaf.leaf_id for leaf in observed),
)
prior = previous[(family_i, direction_i)]
ring_hash = domain_hash(
SCHEMA + "|RING_CHAIN", prior, level, checkpoint_seconds,
family, direction, observed_rows, reflect_2d, collect_3d, signed_2d,
)
rings.append(
Ring(
len(rings), level, checkpoint_seconds,
family_i, family, direction_i, direction,
start, observed_rows, reflect_2d, collect_3d,
signed_2d, prior, ring_hash,
)
)
previous[(family_i, direction_i)] = ring_hash
expected = len(checkpoints) * len(FAMILIES) * len(DIRECTIONS)
if len(rings) != expected:
raise AssertionError("ring population")
return tuple(rings)
def build_cells(source: SourceBundle) -> tuple[Cell, ...]:
cells: list[Cell] = []
for leaf in source.leaves:
for direction_i, direction in enumerate(DIRECTIONS):
flowe_id = domain_hash(
SCHEMA + "|FLOWE_ID", source.hbp_sha256,
leaf.folder_i, leaf.family, leaf.leaf_id, direction,
)
commitments = tuple(
domain_hash(
SCHEMA + "|CELL_COMMITMENT|" + label,
source.hbp_sha256, leaf.folder_i, leaf.family,
leaf.leaf_id, direction, flowe_id,
)
for label in COMMITMENT_LABELS
)
if len(set(commitments)) != len(COMMITMENT_LABELS):
raise AssertionError("domain-separated commitment collision")
cells.append(
Cell(
len(cells), leaf, direction_i, direction, flowe_id,
commitments, # type: ignore[arg-type]
)
)
expected = source.folder_count * len(FAMILIES) * len(DIRECTIONS)
if len(cells) != expected:
raise AssertionError("cell population")
return tuple(cells)
def ring_row(ring: Ring) -> str:
return tuple_row(
"RING", i=ring.index, level=ring.level,
checkpoint_seconds=ring.checkpoint_seconds,
family_i=ring.family_i, family=ring.family,
direction_i=ring.direction_i, direction=ring.direction,
operations="SELF_REFLECT,COLLECT,SELF_REDUCE",
observed_only=1, future_rows=0, observation_limit=OBSERVATION_LIMIT,
window_start=ring.window_start, observed_rows=ring.observed_rows,
transform="2D->3D->SIGNED_2D", reflect_2d_hash=ring.reflect_2d_hash,
collect_3d_hash=ring.collect_3d_hash, signed_2d_hash=ring.signed_2d_hash,
previous_ring_hash=ring.previous_ring_hash, ring_hash=ring.ring_hash,
network=0, execution=0, authority=0, physical_energy=0, json=0,
)
def cell_row(cell: Cell) -> str:
hbi, hbp, sha, sh, hash_value = cell.commitments
leaf = cell.source
return tuple_row(
"FLOWE", i=cell.index, folder_i=leaf.folder_i,
family_i=leaf.family_i, family=leaf.family,
direction_i=cell.direction_i, direction=cell.direction,
source_leaf_i=leaf.index, source_leaf_id=leaf.leaf_id,
source_folder_id=leaf.folder_id, source_tree_commitment=leaf.tree_commitment,
source_object_sha256=leaf.object_sha256, flowe_id=cell.flowe_id,
hbi=hbi, hbp=hbp, sha=sha, sh=sh, hash=hash_value,
commitments_domain_separated=1, commitments_distinct=5,
network=0, execution=0, authority=0, physical_energy=0, json=0,
)
def cell_aggregate_hash(cells: Sequence[Cell]) -> str:
cell_hashes = (
domain_hash(
SCHEMA + "|CELL_OBJECT",
cell.index,
cell.source.index,
cell.source.leaf_id,
cell.direction,
cell.flowe_id,
*cell.commitments,
)
for cell in cells
)
return domain_hash(SCHEMA + "|ALL_CELLS", *cell_hashes)
def build_stdout(source: SourceBundle, journal: Journal) -> bytes:
rows = [
tuple_row(
"FLOWEX9STDOUT", schema=SCHEMA,
timing_mode=journal.timing_mode, target_seconds=journal.target_seconds,
source_hbp_sha256=source.hbp_sha256, checkpoint_count=len(journal.checkpoints),
network=0, execution=0, authority=0, physical_energy=0, json=0,
)
]
rows.extend(
tuple_row(
"OUTWARD", i=item.index, checkpoint_seconds=item.checkpoint_seconds,
session_i=item.session_i, monotonic_session_only=1,
checkpoint_hash=item.checkpoint_hash,
network=0, execution=0, authority=0, physical_energy=0, json=0,
)
for item in journal.checkpoints
)
rows.append(
tuple_row(
"FLOWEX9PASS", complete=1 if journal.complete else 0,
accumulated_seconds=journal.accumulated_seconds,
folders=source.folder_count, families=len(FAMILIES), directions=len(DIRECTIONS),
final_cells=source.folder_count * 9,
ring_summaries=len(journal.checkpoints) * 9,
system_affirmed=0, network=0, execution=0, authority=0,
physical_energy=0, json=0,
)
)
body = ("\n".join(rows) + "\n").encode("utf-8")
rows.append(
tuple_row("FLOWEX9STDOUTFTR", body_sha256=sha256_bytes(body), rows=len(rows) + 1, json=0)
)
return ("\n".join(rows) + "\n").encode("utf-8")
def build_hbp(
source: SourceBundle,
journal: Journal,
rings: Sequence[Ring],
cells: Sequence[Cell],
journal_data: bytes,
) -> tuple[bytes, str]:
expected_rings = len(schedule(journal.target_seconds)) * 9
expected_cells = source.folder_count * 9
if len(rings) != expected_rings or len(cells) != expected_cells:
raise AssertionError("bundle population")
ring_commitment = domain_hash(
SCHEMA + "|ALL_RINGS", *(ring.ring_hash for ring in rings)
)
cell_commitment = cell_aggregate_hash(cells)
object_hash = domain_hash(
SCHEMA + "|OBJECT", source.hbp_sha256, source.hbi_sha256,
sha256_bytes(journal_data), ring_commitment, cell_commitment,
)
rows = [
tuple_row(
"FLOWEX9V2HDR", schema=SCHEMA, status="COMPLETE",
timing_mode=journal.timing_mode,
timing_evidence=(
"MEASURED_MONOTONIC_SESSION_SECONDS"
if journal.timing_mode == "REAL_MONOTONIC"
else (
"DETERMINISTIC_CI_TEST_ONLY"
if journal.timing_mode == "DETERMINISTIC_FAKE_CLOCK"
else "INJECTED_CLOCK_TEST_ONLY"
)
),
target_seconds=journal.target_seconds,
checkpoints=len(schedule(journal.target_seconds)),
folders=source.folder_count, families=3, directions=3,
source_leaves=len(source.leaves), final_cells=len(cells),
ring_summaries=len(rings), observation_limit=OBSERVATION_LIMIT,
system_affirmed=0, network=0, execution=0, authority=0,
physical_energy=0, json=0,
),
tuple_row(
"SOURCE", kind="HBP", file=SOURCE_HBP, bytes=len(source.hbp),
sha256=source.hbp_sha256, exact_sidecar_verified=1, json=0,
),
tuple_row(
"SOURCE", kind="HBI", file=SOURCE_HBI, bytes=len(source.hbi),
sha256=source.hbi_sha256, exact_sidecar_verified=1, json=0,
),
tuple_row(
"JOURNAL", file=OUTPUT_JOURNAL, bytes=len(journal_data),
sha256=sha256_bytes(journal_data), sessions=len(journal.sessions),
accumulated_monotonic_session_seconds=journal.accumulated_seconds,
wall_clock_credit=0, cross_process_gap_credit=0,
uncheckpointed_credit=0, json=0,
),
tuple_row(
"CENTER", nullspace=0, center_members=",".join(CENTER_MEMBERS),
traversal=CENTER_TRAVERSAL, commitments_per_cell=5,
domain_separated=1, sha_equals_hash=0, json=0,
),
tuple_row(
"AXIS", name="FAMILY", members=",".join(FAMILIES), cardinality=3,
independent_from="DIRECTION", json=0,
),
tuple_row(
"AXIS", name="DIRECTION", members=",".join(DIRECTIONS), cardinality=3,
independent_from="FAMILY", json=0,
),
tuple_row(
"TRANSFORM", operations="SELF_REFLECT,COLLECT,SELF_REDUCE",
path="2D->3D->SIGNED_2D", observed_only=1, future_rows=0,
previous_ring_chaining=1, per_level_max_observed=OBSERVATION_LIMIT, json=0,
),
tuple_row(
"BOUNDARY", raw_paths=0, media_bytes_embedded=0,
repository_bytes_embedded=0, credentials=0, network=0,
execution=0, authority=0, physical_energy=0,
physical_light_emitted=0, system_affirmed=0, json=0,
),
]
rows.extend(ring_row(ring) for ring in rings)
rows.extend(cell_row(cell) for cell in cells)
rows.extend(
[
tuple_row(
"HASH", role="FLOWEX9_V2_OBJECT_COMMITMENT", algorithm="SHA256",
value=object_hash, ring_commitment=ring_commitment,
cell_commitment=cell_commitment, distinct_from_hbp_byte_sha=1, json=0,
),
tuple_row(
"SUMMARY", folders=source.folder_count, families=3, directions=3,
final_cells=len(cells), checkpoints=len(schedule(journal.target_seconds)),
ring_summaries=len(rings), commitments_per_cell=5,