agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,1919 @@
1
+ #!/usr/bin/env python3
2
+ """The write-ahead side-effect journal of §10.5 (WP-21 commit 2).
3
+
4
+ Design §10.5: "The side-effect journal is write-ahead: before each effect, a `planned` record
5
+ (durable operation id, target, expected before-hash, intended after-hash) is written and fsynced;
6
+ after the effect, a `done` record." §10.6 then reads it: "a recovery close reads the journal and
7
+ reconciles every `planned` record without `done`".
8
+
9
+ Two properties decide the shape, and both are about what a reader can still trust after a crash.
10
+
11
+ **No effect precedes a SUCCESSFUL fsync of its `planned` record.** `append` returns only after the
12
+ bytes are on the device, and a caller that takes its effect before calling it has the order wrong -
13
+ which `apply` is held to, not this module. The three named seams (`FAULTS`) let a suite inject a
14
+ fault before the write, between the write and the fsync, and after the fsync, with no process
15
+ killed: a crash is not how you test a lost write, because an unsynced write is usually still there
16
+ after one. Losing it needs a storage that drops it, which `LosingStorage` is.
17
+
18
+ **A torn record is detected, not believed.** Each line is `<bytes> <sha256> <json>`: the length and
19
+ the digest of its own payload. A line whose payload is short or whose digest does not match is TORN,
20
+ which is legitimate only at the tail - a crash mid-write - so `read` returns it separately instead of
21
+ raising, and a torn record in the MIDDLE is reported as its own problem, because that is corruption
22
+ rather than an interrupted append.
23
+
24
+ The journal is `runtime_state` in `tables/destinations.json`: it lives outside the run so a run
25
+ directory lost with its machine does not take the record of what was already applied with it. This
26
+ module performs no effect but its own append, which its suite asserts over its AST.
27
+
28
+ journal.py --self-test
29
+ """
30
+ import contextlib
31
+ import errno
32
+ import fcntl
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import pathlib
37
+ import shutil
38
+ import stat
39
+ import sys
40
+ import time
41
+ import unicodedata
42
+
43
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
44
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
45
+ from runlib import destinations, targets # noqa: E402
46
+ from runlib.records import Refused # noqa: E402
47
+
48
+ # §10.5's own four, and the three the plan adds. Held against the design sentence below by
49
+ # `fidelity_problems`, which is done-when 12's "the journal record's required set equals §10.5's".
50
+ # Resolved once at import, by attribute access rather than `getattr(os, ...)`: handing the module
51
+ # to `getattr` is what `dispatch.py` refuses, and the platform question is answered the same way.
52
+ try:
53
+ _NOFOLLOW = os.O_NOFOLLOW
54
+ except AttributeError: # a platform without it; the lexical check is then the only half
55
+ _NOFOLLOW = 0
56
+
57
+ DESIGN_10_5 = (
58
+ "The side-effect journal is write-ahead: before each effect, a `planned` record (durable "
59
+ "operation id, target, expected before-hash, intended after-hash) is written and fsynced; after "
60
+ "the effect, a `done` record.")
61
+ DESIGN_FIELDS = ("operation_id", "target", "before_sha256", "after_sha256")
62
+ PLAN_ADDS = ("item_id", "approval_id")
63
+ # `commit` is on `done` alone: a core item's effect is a commit, and §10.6 reconciles it by finding
64
+ # the operation id in the branch log. `null` where the effect was not a commit.
65
+ DONE_ADDS = ("commit",)
66
+ KINDS = ("planned", "done")
67
+ # The fault seams. A name not in this set is refused rather than ignored, so a misspelled seam in a
68
+ # control cannot quietly test nothing.
69
+ FAULTS = ("before_write", "after_write_before_fsync", "after_fsync")
70
+ _INJECTED = {}
71
+
72
+
73
+ class Injected(Exception):
74
+ """A fault a suite asked for at a named seam. Never raised in production: nothing injects."""
75
+
76
+
77
+ def inject(name, times=1):
78
+ """Arm the named seam. Returns a callable that disarms it, for a `finally`."""
79
+ if name not in FAULTS:
80
+ raise Refused(f"FAULT_UNKNOWN {name}: the seams are {', '.join(FAULTS)}")
81
+ _INJECTED[name] = times
82
+
83
+ def disarm():
84
+ _INJECTED.pop(name, None)
85
+ return disarm
86
+
87
+
88
+ def _seam(name):
89
+ held = _INJECTED.get(name)
90
+ if not held:
91
+ return
92
+ if held <= 1:
93
+ _INJECTED.pop(name, None)
94
+ else:
95
+ _INJECTED[name] = held - 1
96
+ raise Injected(name)
97
+
98
+
99
+ LOCK_NAME = "journal.lock"
100
+ # The wait a writer accepts before refusing by name, and how often it retries. The bound is the
101
+ # point: one stuck holder must not hang every later command (D-20261102-49b466).
102
+ LOCK_WAIT_S = 30.0
103
+ LOCK_RETRY_S = 0.05
104
+
105
+
106
+ def durable(fd):
107
+ """Make what was written to `fd` durable, and return the name of the call that did it.
108
+
109
+ What the platform gives, stated rather than assumed. Plain `fsync(2)` on darwin hands the bytes
110
+ to the DRIVE and does not ask the drive to flush its own write cache, so a power loss can still
111
+ take them; `F_FULLFSYNC` is the request that does. Durability is the whole claim of this record
112
+ — the effect may not precede it — so this asks for `F_FULLFSYNC` where the platform has it, falls
113
+ back to `fsync` where it does not or where the filesystem refuses it, and RETURNS which, so a
114
+ control reads the answer instead of trusting a comment.
115
+ """
116
+ held = getattr(fcntl, "F_FULLFSYNC", None)
117
+ if held is not None:
118
+ try:
119
+ fcntl.fcntl(fd, held)
120
+ return "F_FULLFSYNC"
121
+ except OSError:
122
+ pass # a filesystem that does not implement it: fsync is what there is
123
+ os.fsync(fd)
124
+ return "fsync"
125
+
126
+
127
+ class Confined:
128
+ """The journal's declared root, opened ONCE, with every path under it reached through it.
129
+
130
+ `destinations.inside` answers the LEXICAL question and cannot answer the other one: `os.open`
131
+ follows symlinks, and `O_NOFOLLOW` on the leaf leaves every parent component unguarded. The root
132
+ is therefore opened `O_DIRECTORY|O_NOFOLLOW` once and each component is walked with `dir_fd`, and
133
+ the same handle serves the lock, the read, the append and the reconciliation — one confinement
134
+ rather than four lexical checks, which is what the WP-21 round-2 review found missing (reconcile
135
+ opened the path with a plain `open` after a lexical check).
136
+
137
+ It FAILS CLOSED on what the platform will not give: a root that is not a real directory, or is
138
+ itself a symlink, or whose directory fsync the filesystem refuses, is a root no journal is
139
+ written into. A containment contract that carries on when its own primitive is unavailable is
140
+ not a contract.
141
+ """
142
+
143
+ def __init__(self, root):
144
+ if not root:
145
+ raise Refused("JOURNAL_ROOT_UNDECLARED: the journal's root is run.json's "
146
+ "destinations.runtime_state, and nothing is written without it")
147
+ self.root = pathlib.Path(root)
148
+ try:
149
+ self.fd = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY | _NOFOLLOW)
150
+ except OSError as exc:
151
+ raise Refused(f"JOURNAL_ROOT_UNOPENABLE {self.root}: {exc.strerror} — the declared root "
152
+ f"must be a real directory and not a symlink, or nothing under it can be "
153
+ f"confined") from exc
154
+
155
+ def close(self):
156
+ try:
157
+ os.close(self.fd)
158
+ except OSError:
159
+ pass
160
+
161
+ def __enter__(self):
162
+ return self
163
+
164
+ def __exit__(self, *_exc):
165
+ self.close()
166
+ return False
167
+
168
+ def parts(self, path):
169
+ """The path's components relative to the root, or Refused.
170
+
171
+ The lexical question first, through the module that owns it, so one answer serves both this
172
+ and `destinations`; the components are what the walk then opens one at a time.
173
+ """
174
+ held = pathlib.Path(path)
175
+ if not destinations.inside(held, self.root):
176
+ raise Refused(f"JOURNAL_OUTSIDE_ROOT {held}: not inside the declared runtime_state root "
177
+ f"{str(self.root)!r}")
178
+ relative = os.path.relpath(str(held), str(self.root))
179
+ pieces = [piece for piece in relative.split(os.sep) if piece not in ("", ".")]
180
+ if not pieces or ".." in pieces:
181
+ raise Refused(f"JOURNAL_OUTSIDE_ROOT {held}: its path relative to the root is "
182
+ f"{relative!r}, which names no file under it")
183
+ return pieces
184
+
185
+ def walk(self, pieces, create=False, missing_ok=False):
186
+ """`(fds, leaf)` — one fd per directory from the root down, and the leaf's name.
187
+
188
+ Every component is opened `O_NOFOLLOW`, so a symlink ANYWHERE in the chain is refused rather
189
+ than followed. The fds are returned because the directories themselves have to be fsynced:
190
+ syncing by path would walk the chain again, lexically, which is the hole this closes. The
191
+ caller closes every fd after the root's.
192
+ """
193
+ fds, created = [self.fd], []
194
+ try:
195
+ for piece in pieces[:-1]:
196
+ try:
197
+ held = os.open(piece, os.O_RDONLY | os.O_DIRECTORY | _NOFOLLOW, dir_fd=fds[-1])
198
+ except OSError as exc:
199
+ if exc.errno == errno.ENOENT and missing_ok and not create:
200
+ # Nothing there yet. A READER asking about a journal whose directory has
201
+ # not been created is answered with "no journal", not refused: that is the
202
+ # state before the first append, and §10.6 reads it.
203
+ for held_fd in fds[1:]:
204
+ try:
205
+ os.close(held_fd)
206
+ except OSError:
207
+ pass
208
+ return None, None, []
209
+ if exc.errno == errno.ENOENT and create:
210
+ os.mkdir(piece, 0o700, dir_fd=fds[-1])
211
+ created.append(piece)
212
+ held = os.open(piece, os.O_RDONLY | os.O_DIRECTORY | _NOFOLLOW,
213
+ dir_fd=fds[-1])
214
+ else:
215
+ # WHAT the component is decides, not the errno: a symlink to a directory
216
+ # under `O_DIRECTORY|O_NOFOLLOW` raises ELOOP on Linux and ENOTDIR on
217
+ # darwin, so a rule written on one errno reads a symlink as an ordinary
218
+ # file on the other platform.
219
+ linked = False
220
+ try:
221
+ linked = stat.S_ISLNK(os.lstat(piece, dir_fd=fds[-1]).st_mode)
222
+ except OSError:
223
+ linked = False
224
+ if linked or exc.errno in (errno.ELOOP, errno.EMLINK):
225
+ raise Refused(
226
+ f"JOURNAL_SYMLINK_COMPONENT {'/'.join(pieces)}: {piece} is a "
227
+ f"symbolic link, so the journal would be written wherever it "
228
+ f"points — outside the declared root a lexical check approved"
229
+ ) from exc
230
+ raise Refused(
231
+ f"JOURNAL_PATH_UNWALKABLE {'/'.join(pieces)}: {piece} could not be "
232
+ f"opened ({exc.strerror}), so containment cannot be established"
233
+ ) from exc
234
+ fds.append(held)
235
+ except BaseException:
236
+ for held in fds[1:]:
237
+ try:
238
+ os.close(held)
239
+ except OSError:
240
+ pass
241
+ raise
242
+ return fds, pieces[-1], created
243
+
244
+ def labels(self, pieces):
245
+ """The absolute path of each directory in the chain, for a storage fake and for a report."""
246
+ held, out = self.root, [str(self.root)]
247
+ for piece in pieces[:-1]:
248
+ held = held / piece
249
+ out.append(str(held))
250
+ return out
251
+
252
+ @contextlib.contextmanager
253
+ def lock(self, wait_s=None):
254
+ """The journal's one lock, held across read-validate-truncate and plan-effect-done.
255
+
256
+ Its place is FIXED and declared: `journal.lock` at the top of the declared root, opened
257
+ through this handle. A lock whose path a caller chooses is not a lock — two writers would
258
+ take two different files and both proceed — so there is one name, it is inside the thing it
259
+ protects, and it is reached the same confined way as the journal.
260
+
261
+ `flock` is advisory and per open file description: it serializes every writer that takes
262
+ THIS lock, in this process or another, and it cannot stop a program that writes the journal
263
+ without asking. That is the platform's limit, stated rather than papered over.
264
+ """
265
+ try:
266
+ held = os.open(LOCK_NAME, os.O_RDWR | os.O_CREAT | _NOFOLLOW, 0o600, dir_fd=self.fd)
267
+ except OSError as exc:
268
+ raise Refused(f"JOURNAL_LOCK_UNOPENABLE {self.root / LOCK_NAME}: {exc.strerror}") from exc
269
+ try:
270
+ # BOUNDED, and the bound is the repository's: a writer that waits on `flock` with no
271
+ # deadline hangs every later command on one stuck holder, so an exclusive lock is asked
272
+ # for with LOCK_NB and retried for at most LOCK_WAIT_S, then refused BY NAME
273
+ # (D-20261102-49b466). `runlib/stagelock.py` takes its locks the same way; this module
274
+ # does not import `compose/host_platform.py`'s helper because the payload's stage
275
+ # library does not depend on the installer's.
276
+ waited = LOCK_WAIT_S if wait_s is None else wait_s
277
+ for _attempt in range(int(waited / LOCK_RETRY_S) + 1):
278
+ try:
279
+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
280
+ break
281
+ except BlockingIOError:
282
+ time.sleep(LOCK_RETRY_S)
283
+ else:
284
+ raise Refused(f"JOURNAL_LOCKED {self.root / LOCK_NAME}: another writer has held the "
285
+ f"journal's lock for {waited:g} s, so this one refuses rather than "
286
+ f"waiting without a deadline")
287
+ yield held
288
+ finally:
289
+ try:
290
+ fcntl.flock(held, fcntl.LOCK_UN)
291
+ finally:
292
+ os.close(held)
293
+
294
+
295
+ class Storage:
296
+ """The real device: append the bytes, then make the file and its whole directory chain durable.
297
+
298
+ The directory sync is what makes a newly created journal file's own NAME durable; without it the
299
+ file's bytes can be on the device while the entry that reaches them is not. The WHOLE chain is
300
+ synced on every append, not only the parts this append created: `mkdir(parents=True)` can leave
301
+ `a/b` behind after a failed sync, and the retry then finds nothing new to create and syncs
302
+ nothing — the record is durable inside directory entries that never reached the device. There is
303
+ no way to ask the kernel whether an entry is already durable, so the answer is to sync the chain
304
+ unconditionally, which costs a handful of fsyncs and closes the hole (the WP-21 round-2 review).
305
+ """
306
+
307
+ def _write_once(self, handle, data):
308
+ """One write to the device, as its own named seam.
309
+
310
+ A seam rather than a patch: a control that swaps `os.write` out hands an executor's module
311
+ around, which `dispatch.py`'s source-shape rule refuses in a shipped module — rightly, since
312
+ replacing a module is how an effect hides from a scan. Overriding one method needs nothing
313
+ global swapped, and it matches this unit's decision that faults arrive through named seams.
314
+ """
315
+ return os.write(handle, data)
316
+
317
+ def _single_name(self, handle, pieces):
318
+ """Refuse a journal whose bytes have a second name.
319
+
320
+ `O_NOFOLLOW` refuses a symlink and says nothing of a hard link: the open succeeds and the
321
+ bytes it reaches may be a file outside the declared root, under its other name. Appending or
322
+ truncating through this name then changes that file (the round-5 review). The descriptor is
323
+ asked, after the open and before any byte moves.
324
+ """
325
+ held = os.fstat(handle)
326
+ if not stat.S_ISREG(held.st_mode) or held.st_nlink != 1:
327
+ raise Refused(f"JOURNAL_HARD_LINKED {'/'.join(pieces)}: the journal is not a regular "
328
+ f"file with exactly one name (links: {held.st_nlink}), so writing it "
329
+ f"here would change bytes this root does not confine")
330
+
331
+ def append(self, confined, pieces, data):
332
+ """Append `data` to the journal named by `pieces`, under the confined root."""
333
+ fds, leaf, _created = confined.walk(pieces, create=True)
334
+ labels = confined.labels(pieces)
335
+ try:
336
+ existed = True
337
+ try:
338
+ os.stat(leaf, dir_fd=fds[-1], follow_symlinks=False)
339
+ except OSError:
340
+ existed = False
341
+ _seam("before_write")
342
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | _NOFOLLOW
343
+ try:
344
+ handle = os.open(leaf, flags, 0o600, dir_fd=fds[-1])
345
+ except OSError as exc:
346
+ if exc.errno in (errno.ELOOP, errno.EMLINK):
347
+ raise Refused(f"JOURNAL_SYMLINK {'/'.join(pieces)}: the journal path is a "
348
+ f"symlink, so the append would land wherever it points — outside "
349
+ f"the declared root that a lexical check just approved") from exc
350
+ raise
351
+ try:
352
+ self._single_name(handle, pieces)
353
+ # A SHORT write is not a complete record. `os.write` may write fewer bytes than it
354
+ # was given, and returning then would acknowledge a durable complete record for a
355
+ # line the reader will see as torn. Loop until every byte is written, and fail by
356
+ # name if the device stops accepting them.
357
+ written = 0
358
+ while written < len(data):
359
+ held = self._write_once(handle, data[written:])
360
+ if held <= 0:
361
+ raise Refused(f"JOURNAL_SHORT_WRITE {'/'.join(pieces)}: the device accepted "
362
+ f"{written} of {len(data)} bytes and then none, so the record "
363
+ f"is incomplete")
364
+ written += held
365
+ _seam("after_write_before_fsync")
366
+ self._durable_file(handle, labels[-1] + "/" + leaf, created=not existed)
367
+ finally:
368
+ os.close(handle)
369
+ for index, held_fd in enumerate(fds):
370
+ self._sync_directory(held_fd, labels[index])
371
+ _seam("after_fsync")
372
+ finally:
373
+ for held_fd in fds[1:]:
374
+ try:
375
+ os.close(held_fd)
376
+ except OSError:
377
+ pass
378
+
379
+ def read_bytes(self, confined, pieces):
380
+ """The journal's bytes, through the same confined handle. Empty when it is not there yet."""
381
+ fds, leaf, _created = confined.walk(pieces, missing_ok=True)
382
+ if fds is None:
383
+ return None
384
+ try:
385
+ try:
386
+ handle = os.open(leaf, os.O_RDONLY | _NOFOLLOW, dir_fd=fds[-1])
387
+ except OSError as exc:
388
+ if exc.errno == errno.ENOENT:
389
+ return None
390
+ if exc.errno in (errno.ELOOP, errno.EMLINK):
391
+ raise Refused(f"JOURNAL_SYMLINK {'/'.join(pieces)}: the journal path is a "
392
+ f"symlink, so a read would come from wherever it points") from exc
393
+ raise
394
+ try:
395
+ held = []
396
+ while True:
397
+ chunk = os.read(handle, 1 << 20)
398
+ if not chunk:
399
+ break
400
+ held.append(chunk)
401
+ return b"".join(held)
402
+ finally:
403
+ os.close(handle)
404
+ finally:
405
+ for held_fd in fds[1:]:
406
+ try:
407
+ os.close(held_fd)
408
+ except OSError:
409
+ pass
410
+
411
+ def truncate(self, confined, pieces, cut):
412
+ """Cut the journal to `cut` bytes, durably, through the same confined handle."""
413
+ fds, leaf, _created = confined.walk(pieces)
414
+ labels = confined.labels(pieces)
415
+ try:
416
+ handle = os.open(leaf, os.O_RDWR | _NOFOLLOW, dir_fd=fds[-1])
417
+ try:
418
+ self._single_name(handle, pieces)
419
+ os.ftruncate(handle, cut)
420
+ self._durable_file(handle, labels[-1] + "/" + leaf, created=False)
421
+ finally:
422
+ os.close(handle)
423
+ for index, held_fd in enumerate(fds):
424
+ self._sync_directory(held_fd, labels[index])
425
+ finally:
426
+ for held_fd in fds[1:]:
427
+ try:
428
+ os.close(held_fd)
429
+ except OSError:
430
+ pass
431
+
432
+ def _durable_file(self, handle, label, created):
433
+ """The file's CONTENTS made durable. `created` says whether its name is new.
434
+
435
+ Three things are at risk and they are lost separately: the contents, the file's own entry in
436
+ its directory, and the entries of the directories above it. A fake that models fewer than
437
+ three cannot show the loss of the ones it skipped, which is how a journal whose own directory
438
+ entry never landed stayed invisible to a suite that had a storage fake in it.
439
+ """
440
+ durable(handle)
441
+
442
+ def _dir_sync_call(self, held_fd):
443
+ """The platform call itself, as its own seam.
444
+
445
+ A seam so the translation below can be shown to fire: a filesystem that refuses to fsync a
446
+ directory is a real configuration, and the only way to exercise this module's answer to it
447
+ without one is to override the call.
448
+ """
449
+ return durable(held_fd)
450
+
451
+ def _sync_directory(self, held_fd, label):
452
+ """One directory's entries made durable, by fd.
453
+
454
+ By fd rather than by path: syncing by path walks the chain a second time, lexically, which
455
+ is the hole the confined handle closes. A filesystem that refuses the request is a
456
+ filesystem this module will not claim durability on.
457
+ """
458
+ try:
459
+ self._dir_sync_call(held_fd)
460
+ except OSError as exc:
461
+ if exc.errno in (errno.EINVAL, errno.ENOTSUP):
462
+ raise Refused(f"JOURNAL_DIRECTORY_SYNC_UNSUPPORTED {label}: the filesystem refuses "
463
+ f"to fsync a directory ({exc.strerror}), so a new journal's own name "
464
+ f"cannot be made durable here and no durability is claimed") from exc
465
+ raise
466
+
467
+
468
+ class LosingStorage(Storage):
469
+ """A storage that keeps unsynced writes in memory and loses them on demand.
470
+
471
+ The only honest way to exercise §10.5's "no effect precedes a successful fsync": a killed process
472
+ does NOT lose an unsynced write on a real filesystem, so a control built on a crash would be
473
+ asserting something the platform does not do. `lose_unsynced()` is the storage failure.
474
+
475
+ Three things are at risk and a real filesystem loses them SEPARATELY: the contents, the journal
476
+ file's own entry in its directory, and the entries of the directories created above it. This fake
477
+ modelled two, so a new journal under an EXISTING directory could not be shown to disappear at all
478
+ (the WP-21 round-2 review). `lose_names=True` is that third model: the bytes are written and the
479
+ file is fsynced, and the directory entries are not, which is exactly the state in which a file
480
+ exists on the device and nothing can reach it.
481
+ """
482
+
483
+ def __init__(self, lose_names=False):
484
+ self.unsynced = []
485
+ self.unsynced_directories = []
486
+ self.unsynced_files = []
487
+ self.synced = []
488
+ self.roots = set()
489
+ self.lose_names = lose_names
490
+ self._flushing = False
491
+
492
+ def _durable_file(self, handle, label, created):
493
+ """While flushing, the contents really are made durable; the NAME may still be at risk."""
494
+ if not self._flushing:
495
+ return
496
+ Storage._durable_file(self, handle, label, created)
497
+ if created and self.lose_names:
498
+ self.unsynced_files.append(pathlib.Path(label))
499
+
500
+ def _sync_directory(self, held_fd, label):
501
+ """Recorded always; performed only while flushing, and not at all under `lose_names`.
502
+
503
+ A directory that really was synced leaves the loss list. Without that the fake lost entries
504
+ a real device would have kept, so every control built on it was watching the fake's own
505
+ bookkeeping rather than the durability rule (the round-3 review).
506
+ """
507
+ self.synced.append(str(label))
508
+ if self._flushing and not self.lose_names:
509
+ Storage._sync_directory(self, held_fd, label)
510
+ held_path = pathlib.Path(label)
511
+ self.unsynced_directories = [p for p in self.unsynced_directories if p != held_path]
512
+
513
+ def append(self, confined, pieces, data):
514
+ self.roots.add(str(confined.root))
515
+ fds, leaf, created = confined.walk(pieces, create=True)
516
+ labels = confined.labels(pieces)
517
+ try:
518
+ for index, piece in enumerate(pieces[:-1]):
519
+ if piece in created:
520
+ self._created_directory(pathlib.Path(labels[index + 1]))
521
+ _seam("before_write")
522
+ self.unsynced.append((confined, list(pieces), data))
523
+ _seam("after_write_before_fsync")
524
+ held_writes, self.unsynced = self.unsynced, []
525
+ self._flushing = True
526
+ try:
527
+ for held_confined, held_pieces, held_data in held_writes:
528
+ Storage.append(self, held_confined, held_pieces, held_data)
529
+ finally:
530
+ self._flushing = False
531
+ _seam("after_fsync")
532
+ finally:
533
+ for held_fd in fds[1:]:
534
+ try:
535
+ os.close(held_fd)
536
+ except OSError:
537
+ pass
538
+
539
+ def _created_directory(self, made):
540
+ """A directory ENTRY that has not reached the device yet.
541
+
542
+ An entry that never landed takes everything under it with it, because nothing can reach what
543
+ has no name.
544
+ """
545
+ self.unsynced_directories.append(pathlib.Path(made))
546
+
547
+ def lose_unsynced(self):
548
+ """Discard every write, file name and directory entry that was not made durable.
549
+
550
+ Returns `{contents, files, directories}`: the three are lost separately on a real
551
+ filesystem, and a caller that counted only contents could not see a journal whose own name
552
+ never landed.
553
+ """
554
+ held = len(self.unsynced)
555
+ files = [p for p in self.unsynced_files if p.exists()]
556
+ directories = [p for p in self.unsynced_directories if p.exists()]
557
+ self.unsynced = []
558
+ self.unsynced_files = []
559
+ self.unsynced_directories = []
560
+ lost_files = 0
561
+ for held_file in sorted({str(p) for p in files}):
562
+ try:
563
+ pathlib.Path(held_file).unlink()
564
+ lost_files += 1
565
+ except OSError:
566
+ pass
567
+ # The entries go from the DEEPEST created downwards, the order a device that never got them
568
+ # would have left the tree in.
569
+ lost_directories = 0
570
+ for directory in sorted({str(p) for p in directories}, key=len, reverse=True):
571
+ held_path = pathlib.Path(directory)
572
+ if not held_path.is_dir() or held_path == held_path.parent:
573
+ continue
574
+ if str(held_path) in self.roots:
575
+ raise Refused(f"STORAGE_FAKE_WOULD_REMOVE_ROOT {held_path}: a declared journal root "
576
+ f"reached the loss list, which no append can cause and no fake may do")
577
+ shutil.rmtree(held_path, ignore_errors=True)
578
+ lost_directories += 1
579
+ return {"contents": held, "files": lost_files, "directories": lost_directories}
580
+
581
+
582
+ def frame(record):
583
+ """One line: the payload's byte length, its sha256, and the payload."""
584
+ payload = json.dumps(record, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
585
+ data = payload.encode("utf-8")
586
+ return f"{len(data)} {hashlib.sha256(data).hexdigest()} {payload}\n".encode("utf-8")
587
+
588
+
589
+ def record_problems(record):
590
+ """What is wrong with one record, by name. Empty means it may be appended."""
591
+ problems = []
592
+ kind = record.get("kind")
593
+ if kind not in KINDS:
594
+ problems.append(f"JOURNAL_KIND {kind!r}: a record is {' or '.join(KINDS)}")
595
+ return problems
596
+ required = DESIGN_FIELDS + PLAN_ADDS + (DONE_ADDS if kind == "done" else ())
597
+ for field in required:
598
+ if field not in record:
599
+ problems.append(f"JOURNAL_FIELD_ABSENT {kind}.{field}: §10.5's record names it")
600
+ extra = sorted(set(record) - set(required) - {"kind"})
601
+ if extra:
602
+ problems.append(f"JOURNAL_FIELD_UNDECLARED {kind}: {', '.join(extra)}")
603
+ for field in ("operation_id", "target", "item_id", "approval_id"):
604
+ value = record.get(field)
605
+ if field not in record:
606
+ continue
607
+ if not isinstance(value, str) or not value:
608
+ problems.append(f"JOURNAL_VALUE {kind}.{field}: a non-empty string, not {value!r}")
609
+ continue
610
+ # No character that a reader, a renderer or a path could read as structure. These values are
611
+ # written into a line-delimited journal and the target is opened by an effect: a Unicode
612
+ # line separator in a target was accepted, and `str.splitlines` — which other readers in
613
+ # this repo still use — would have split the record at it. The framing itself now carries
614
+ # any payload (that is `read`'s job); what a legal RECORD may hold is this rule's.
615
+ held_bad = sorted({repr(ch) for ch in value
616
+ if unicodedata.category(ch) in targets.CONTROL_CATEGORIES})
617
+ if held_bad:
618
+ problems.append(f"JOURNAL_CONTROL_CHARACTER {kind}.{field}: {', '.join(held_bad)} is "
619
+ f"not admissible in a value this journal carries on one line")
620
+ target = record.get("target")
621
+ if isinstance(target, str) and target:
622
+ # The target is a path an effect will open, and ONE contract says what it names:
623
+ # `runlib/targets.py`. These rules were a second copy, and the copies disagreed — this one
624
+ # accepted `./claude/CLAUDE.md` where `drift` refused the same spelling, so an approval was
625
+ # valid or invalid according to which surface was asked (the round-2 review). The codes keep
626
+ # the `JOURNAL_` namespace by prefix, so a record still says which surface judged it while
627
+ # the rule has one owner.
628
+ for held in targets.lexical_problems(target):
629
+ code, _, detail = held.partition(" ")
630
+ problems.append(f"JOURNAL_{code} {kind}: {detail}" if detail
631
+ else f"JOURNAL_{code} {kind}")
632
+ return problems
633
+
634
+
635
+ def planned(operation_id, target, before_sha256, after_sha256, item_id, approval_id):
636
+ """A `planned` record, refused if it is not one."""
637
+ held = {"kind": "planned", "operation_id": operation_id, "target": target,
638
+ "before_sha256": before_sha256, "after_sha256": after_sha256, "item_id": item_id,
639
+ "approval_id": approval_id}
640
+ problems = record_problems(held)
641
+ if problems:
642
+ raise Refused("; ".join(problems))
643
+ return held
644
+
645
+
646
+ def done(operation_id, target, before_sha256, after_sha256, item_id, approval_id, commit=None):
647
+ """A `done` record, refused if it is not one."""
648
+ held = {"kind": "done", "operation_id": operation_id, "target": target,
649
+ "before_sha256": before_sha256, "after_sha256": after_sha256, "item_id": item_id,
650
+ "approval_id": approval_id, "commit": commit}
651
+ problems = record_problems(held)
652
+ if problems:
653
+ raise Refused("; ".join(problems))
654
+ return held
655
+
656
+
657
+ def plan_digest(record):
658
+ """The identity of an operation: the sha256 of its WHOLE plan.
659
+
660
+ Keyed on `operation_id` alone, two different plans were one operation: `journalled` compared the
661
+ id and the kind, so an OLDER plan already in the journal satisfied the durability check for a new
662
+ one, and the new plan's effect ran against a record that described something else. The digest is
663
+ over every field of the plan but its kind, canonically, so "the same operation" means the same
664
+ plan and nothing looser (the WP-21 round-2 review).
665
+ """
666
+ held = {key: value for key, value in (record or {}).items() if key != "kind"}
667
+ return hashlib.sha256(json.dumps(held, sort_keys=True, ensure_ascii=False,
668
+ separators=(",", ":")).encode("utf-8")).hexdigest()
669
+
670
+
671
+ def _read_bytes(confined, pieces, storage):
672
+ blob = storage.read_bytes(confined, pieces)
673
+ return b"" if blob is None else blob
674
+
675
+
676
+ def _parse(blob):
677
+ """`read`'s answer over bytes already in hand, so a reader under the lock re-reads nothing."""
678
+ return _records_of(blob)
679
+
680
+
681
+ def operation_problems(records, record):
682
+ """Why this operation may not be planned now, by name — three different answers.
683
+
684
+ A retry is not a re-execution. The three states a journal can already be in for one operation id
685
+ are different situations with different answers, and `journalled` ran the effect again in all
686
+ three: it only asked whether a record with that id and kind existed.
687
+
688
+ * COMPLETED — a `done` record is there. The effect happened; running it again is the duplicate
689
+ the journal exists to prevent.
690
+ * CONFLICTING — a `planned` record is there with a DIFFERENT plan. The id has been reused for
691
+ another operation, and neither plan may be taken as the other's durability.
692
+ * UNRECONCILED — a `planned` record with the same plan and no `done`. This is a retry, and it
693
+ belongs to recovery (§10.6): whether the effect happened is exactly what the journal cannot
694
+ say, so the callback is not called again here.
695
+ """
696
+ held = plan_digest(record)
697
+ problems = []
698
+ # A plan whose `done` is in the journal is COMPLETED and nothing else. Asked row by row, the
699
+ # planned row of a finished operation also answered UNRECONCILED - "no done record" - ahead of
700
+ # the done row's answer, and sent a retry of finished work to recovery (the round-8 review).
701
+ completed = any(row.get("operation_id") == record.get("operation_id") and row.get("kind") == "done"
702
+ for row in records)
703
+ for row in records:
704
+ if row.get("operation_id") != record.get("operation_id"):
705
+ continue
706
+ if row.get("kind") == "done":
707
+ problems.append(f"JOURNAL_OPERATION_COMPLETED {record.get('operation_id')}: the journal "
708
+ f"already holds a done record for it, so the effect has been taken and "
709
+ f"taking it again is the duplicate this journal exists to prevent")
710
+ elif row.get("kind") == "planned":
711
+ if plan_digest(row) != held:
712
+ problems.append(f"JOURNAL_OPERATION_CONFLICTING {record.get('operation_id')}: the "
713
+ f"journal holds another plan under this id ({plan_digest(row)[:12]}… "
714
+ f"against {held[:12]}…), so neither can serve as the other's "
715
+ f"durability")
716
+ elif not completed:
717
+ problems.append(f"JOURNAL_OPERATION_UNRECONCILED {record.get('operation_id')}: a "
718
+ f"plan for it is durable with no done record, which is what §10.6's "
719
+ f"recovery decides; a retry enters recovery and does not re-run the "
720
+ f"effect")
721
+ return problems
722
+
723
+
724
+ def append(path, record, root, storage=None):
725
+ """Append one record, durably, and return it. Refuses before writing anything.
726
+
727
+ `root` is the journal's declared root (`run.json.destinations.runtime_state`): a journal written
728
+ outside it is the hole `destinations.py` exists to close, and the question is asked through that
729
+ module so one answer serves both. Every byte goes through ONE confined handle on that root, and
730
+ read-validate-write happens under the journal's one lock.
731
+ """
732
+ storage = storage or Storage()
733
+ with Confined(root) as confined:
734
+ pieces = confined.parts(path)
735
+ problems = record_problems(record)
736
+ if problems:
737
+ raise Refused("; ".join(problems))
738
+ with confined.lock():
739
+ _validate_before_append(confined, pieces, storage, path)
740
+ storage.append(confined, pieces, frame(record))
741
+ return record
742
+
743
+
744
+ def _validate_before_append(confined, pieces, storage, path):
745
+ """What must be true of the journal before anything is added to it, read under the lock.
746
+
747
+ An unterminated tail is reconciled first: appending blindly put the new frame on the same line
748
+ as the torn one, and recovery then read ONE unframed line where two records had been written —
749
+ the second durable and invisible. §10.6 expects a torn tail; it does not expect the next append
750
+ to bury it.
751
+
752
+ A complete line whose frame does not verify is CORRUPTION, not an interrupted write, and no
753
+ append or effect proceeds over it: `read`'s problems were computed and ignored, so `journalled`
754
+ appended a plan and ran an effect on a journal already reported as damaged in the middle. Tail
755
+ repair and corruption recovery stay apart — the first is mechanical, the second is a decision.
756
+ """
757
+ held = _parse(_read_bytes(confined, pieces, storage))
758
+ if held["problems"]:
759
+ raise Refused(f"JOURNAL_CORRUPT {path}: {'; '.join(held['problems'])}. An append and any "
760
+ f"effect are refused over a journal with complete-line corruption; tail "
761
+ f"repair does not touch it and recovery decides what does")
762
+ if held["torn"] and held.get("unterminated"):
763
+ raise Refused(f"JOURNAL_TAIL_UNRECONCILED {path}: the last line carries no newline, so an "
764
+ f"append would put two records on one line. Reconcile the tail "
765
+ f"(`reconcile_tail`) before adding to this journal")
766
+ return held
767
+
768
+
769
+ def journalled(path, record, root, effect, storage=None):
770
+ """Append the plan, take the effect, append the done record. Returns both records.
771
+
772
+ The API a future effect loop calls, and the reason it exists: §10.5's ordering is "no effect
773
+ precedes a successful fsync", and nothing in this module could show that an effect WAITED,
774
+ because the only ordering control appended a record and then looked at the journal. It invoked no
775
+ effect, created no target and held no before-state, so it would have passed over a loop that took
776
+ the effect first.
777
+
778
+ `effect` is called with no arguments and its return value is carried into the done record's
779
+ `result`. It is called EXACTLY ONCE, after the plan record is durable, and not at all when the
780
+ append refuses, when the storage loses the write, or when the journal already knows this
781
+ operation — completed, conflicting or unreconciled, three different refusals. Calling it twice
782
+ with one id ran the effect twice; that is now a refusal by name.
783
+
784
+ The whole sequence — read, validate, plan, effect, done — is under the journal's ONE lock, held
785
+ across all of it. A lock taken per write would let another writer append between the plan and the
786
+ done record, and the reconciliation that reads this journal cannot tell that interleaving from a
787
+ crash.
788
+ """
789
+ storage = storage or Storage()
790
+ problems = record_problems(record)
791
+ if problems:
792
+ raise Refused("; ".join(problems))
793
+ with Confined(root) as confined:
794
+ pieces = confined.parts(path)
795
+ with confined.lock():
796
+ held = _validate_before_append(confined, pieces, storage, path)
797
+ refusals = operation_problems(held["records"], record)
798
+ if refusals:
799
+ raise Refused("; ".join(refusals))
800
+ storage.append(confined, pieces, frame(record))
801
+ # Durable only if the journal now actually holds it: a storage that lost the unsynced
802
+ # write has told us nothing was written, and the effect must not run. The plan is
803
+ # recognised by its DIGEST, not by its id — an older plan under the same id used to
804
+ # satisfy this check for a new one.
805
+ after = _parse(_read_bytes(confined, pieces, storage))
806
+ # The WHOLE parse, before anything irreversible: the pre-append validation cannot see a
807
+ # journal this very append damaged, and `after` was searched for one record while its
808
+ # own problems went unread. A journal that does not parse is not a journal an effect may
809
+ # stand on.
810
+ if after["problems"]:
811
+ raise Refused(f"JOURNAL_CORRUPT {path}: {'; '.join(after['problems'])} — the "
812
+ f"journal does not parse after the append, so the effect is not "
813
+ f"taken and tail repair does not touch it")
814
+ if not any(row.get("kind") == "planned" and plan_digest(row) == plan_digest(record)
815
+ for row in after["records"]):
816
+ raise Refused(f"JOURNAL_PLAN_NOT_DURABLE {path}: the plan for "
817
+ f"{record.get('operation_id')!r} is not in the journal after the "
818
+ f"append, so the effect is not taken")
819
+ result = effect()
820
+ finished = done(record["operation_id"], record["target"], record["before_sha256"],
821
+ record["after_sha256"], record["item_id"], record["approval_id"],
822
+ commit=result if isinstance(result, str) else None)
823
+ storage.append(confined, pieces, frame(finished))
824
+ return {"planned": record, "done": finished, "result": result}
825
+
826
+
827
+ def reconcile_tail(path, root, storage=None):
828
+ """Truncate an unterminated tail so appending is safe again, and say what was dropped.
829
+
830
+ The tail is returned rather than silently discarded: an interrupted append is a record somebody
831
+ may want to look at, and recovery (§10.6) is the reader that decides. Only a tail with no newline
832
+ is removed — a complete line whose frame does not verify is corruption, not an interrupted write,
833
+ and this does not touch it.
834
+
835
+ Read, validate and truncate happen under the SAME lock and through the SAME confined handle as an
836
+ append. Before, this read the bytes, computed the cut, and then reopened the path with a plain
837
+ `open` to truncate: another recovery could repair the tail and append a record in between, and
838
+ the truncation then cut a record that had been made durable after the read (the WP-21 round-2
839
+ review). Under the lock, the bytes are re-read and the tail re-identified immediately before the
840
+ cut, so the length this truncates to is the length it just measured.
841
+ """
842
+ storage = storage or Storage()
843
+ with Confined(root) as confined:
844
+ pieces = confined.parts(path)
845
+ with confined.lock():
846
+ blob = storage.read_bytes(confined, pieces)
847
+ if blob is None:
848
+ return {"dropped": None}
849
+ if not blob or blob.endswith(b"\n"):
850
+ return {"dropped": None}
851
+ cut = blob.rfind(b"\n") + 1
852
+ dropped = blob[cut:]
853
+ # Re-measured under the lock, immediately before the cut. Equal bytes are what licenses
854
+ # the truncation; anything else means the journal moved and this answer is stale.
855
+ again = storage.read_bytes(confined, pieces)
856
+ if again != blob:
857
+ raise Refused(f"JOURNAL_MOVED_UNDER_RECONCILE {path}: the journal changed between "
858
+ f"the read and the truncation ({len(blob)} bytes then "
859
+ f"{len(again or b'')}), so the cut this computed is not the cut this "
860
+ f"file needs")
861
+ storage.truncate(confined, pieces, cut)
862
+ return {"dropped": dropped.decode("utf-8", errors="replace")}
863
+
864
+
865
+ def read(path):
866
+ """`{records, torn, problems}` — the journal as a reader may trust it.
867
+
868
+ A torn line is returned rather than raised: at the tail it is an interrupted append, which §10.6
869
+ expects. One anywhere else is corruption and is named as a problem, because an append cannot tear
870
+ a line that already has a line after it.
871
+
872
+ Reading takes no lock: recovery is allowed to look at a journal mid-append, and that is the
873
+ reading §10.6 does. What may not happen without the lock is deciding or writing, which is why
874
+ `append`, `journalled` and `reconcile_tail` re-read the bytes through the confined handle under
875
+ it rather than calling this.
876
+ """
877
+ path = pathlib.Path(path)
878
+ if not path.is_file():
879
+ return {"records": [], "torn": [], "problems": [], "unterminated": False}
880
+ return _records_of(path.read_bytes())
881
+
882
+
883
+ def _records_of(blob):
884
+ """One parser for the journal's bytes, whoever is holding them.
885
+
886
+ The locked path reads the bytes through the confined handle and this turns them into records, so
887
+ a reader under the lock and a reader outside it cannot disagree about what the file says.
888
+ """
889
+ unterminated = bool(blob) and not blob.endswith(b"\n")
890
+ pieces = blob.split(b"\n")
891
+ if pieces and pieces[-1] == b"":
892
+ pieces = pieces[:-1]
893
+ records, torn, problems = [], [], []
894
+ for number, raw in enumerate(pieces, start=1):
895
+ last = number == len(pieces)
896
+ try:
897
+ line = raw.decode("utf-8")
898
+ except UnicodeDecodeError:
899
+ line = None
900
+ held = None if line is None else _unframe(line)
901
+ if held is None or (last and unterminated):
902
+ # An unterminated tail is torn even when the bytes before it frame correctly: the
903
+ # delimiter is part of the record, and a reader that accepts the frame without it
904
+ # cannot tell a finished append from one that stopped before its newline.
905
+ torn.append({"line": number, "text": (line or repr(raw))[:120],
906
+ "why": "no trailing newline" if held is not None else "unframed"})
907
+ # An append is interrupted BEFORE its newline, so the only line a tear can explain is a
908
+ # last line with no newline. Any other unframed line is corruption, and the final one
909
+ # was the hole: a complete last line that framed nowhere went into `torn` with no
910
+ # problem at all, so `append` and `journalled` ran over it (the round-3 review).
911
+ if not last:
912
+ problems.append(f"JOURNAL_TORN_MIDDLE line {number}: a line with lines after it "
913
+ f"cannot have been torn by an append, so this is corruption")
914
+ elif not unterminated:
915
+ problems.append(f"JOURNAL_CORRUPT_LINE line {number}: the last line carries its "
916
+ f"newline and frames nowhere, so no interrupted append explains it "
917
+ f"— this is corruption, and tail repair does not touch it")
918
+ continue
919
+ records.append(held)
920
+ return {"records": records, "torn": torn, "problems": problems,
921
+ "unterminated": unterminated}
922
+
923
+
924
+ def _unframe(line):
925
+ """The record a framed line carries, or None when the line is torn."""
926
+ head, _, payload = line.partition(" ")
927
+ digest, _, payload = payload.partition(" ")
928
+ if not head.isdigit() or len(digest) != 64:
929
+ return None
930
+ data = payload.encode("utf-8")
931
+ if len(data) != int(head) or hashlib.sha256(data).hexdigest() != digest:
932
+ return None
933
+ try:
934
+ held = json.loads(payload)
935
+ except ValueError:
936
+ return None
937
+ return held if isinstance(held, dict) else None
938
+
939
+
940
+ def pending(records):
941
+ """Every `planned` operation with no `done`, in the order they were planned.
942
+
943
+ What §10.6 reconciles. Keyed by operation id, because that is the durable identity: a target can
944
+ carry several operations in one run and each is reconciled on its own.
945
+ """
946
+ finished = {row["operation_id"] for row in records if row.get("kind") == "done"}
947
+ held, seen = [], set()
948
+ for row in records:
949
+ if row.get("kind") != "planned":
950
+ continue
951
+ operation = row.get("operation_id")
952
+ if operation in finished or operation in seen:
953
+ continue
954
+ seen.add(operation)
955
+ held.append(row)
956
+ return held
957
+
958
+
959
+ # Each required field paired with the PHRASE §10.5 names it by. A parameter so the suite can hand
960
+ # this check a SHORTENED list and watch it say so: a coverage check whose own list is the thing that
961
+ # can shrink has no negative control otherwise.
962
+ DESIGN_PHRASES = (("operation_id", "durable operation id"), ("target", "target"),
963
+ ("before_sha256", "expected before-hash"), ("after_sha256", "intended after-hash"))
964
+
965
+
966
+ def fidelity_problems(phrases=DESIGN_PHRASES):
967
+ """The required sets against §10.5's sentence (done-when 12), and the seams against their list."""
968
+ problems = []
969
+ # Each required field paired with the PHRASE §10.5 names it by, so the check reads the sentence
970
+ # rather than a mangling of it: the first version stripped characters until "operation id"
971
+ # became "operationid" and then failed on a sentence that says it.
972
+ named = phrases
973
+ if sorted(field for field, _phrase in named) != sorted(DESIGN_FIELDS):
974
+ problems.append(f"DESIGN_FIELD_SET: this check covers "
975
+ f"{', '.join(sorted(field for field, _p in named))}, the required set is "
976
+ f"{', '.join(sorted(DESIGN_FIELDS))}")
977
+ for field, phrase in named:
978
+ if phrase not in DESIGN_10_5:
979
+ problems.append(f"DESIGN_FIELD_UNNAMED {field}: §10.5's sentence here does not say "
980
+ f"{phrase!r}")
981
+ for kind in KINDS:
982
+ if f"`{kind}` record" not in DESIGN_10_5:
983
+ problems.append(f"DESIGN_KIND_UNNAMED {kind}: §10.5's sentence here does not name it")
984
+ if "fsynced" not in DESIGN_10_5:
985
+ problems.append("DESIGN_FSYNC_UNNAMED: the sentence no longer says the record is fsynced, "
986
+ "which is the whole order this module exists to keep")
987
+ return problems
988
+
989
+
990
+ def document():
991
+ """What this module is, for a reader deciding whether to trust the journal."""
992
+ return {"design": DESIGN_10_5, "kinds": list(KINDS),
993
+ "planned_fields": list(DESIGN_FIELDS + PLAN_ADDS),
994
+ "done_fields": list(DESIGN_FIELDS + PLAN_ADDS + DONE_ADDS),
995
+ "seams": list(FAULTS),
996
+ "framing": "<payload byte length> <sha256 of the payload> <payload json>"}
997
+
998
+
999
+ def _short_write_probe(path, record, root=None):
1000
+ """Append with the device accepting one byte and then zero: the short-write refusal's own case.
1001
+
1002
+ A real short write cannot be arranged on demand, so it arrives through `Storage._write_once`, a
1003
+ named seam. It was `unittest.mock.patch.object(os, "write", ...)` until `dispatch.py`'s
1004
+ source-shape rule refused handing an executor's module to anybody from a shipped module — which
1005
+ is right, and the seam is the better shape anyway: nothing global is swapped.
1006
+ """
1007
+ calls = {"n": 0}
1008
+
1009
+ def short(_handle, data):
1010
+ calls["n"] += 1
1011
+ # The cap is what makes this a control rather than a hang. With the `held <= 0` refusal
1012
+ # reverted, a device returning zero forever spins the loop forever: a revert trial over the
1013
+ # unbounded probe stopped reporting and timed out at fifteen minutes with nothing said. The
1014
+ # cap turns that into a named exception, so the trial reads "the guard is load-bearing"
1015
+ # instead of waiting.
1016
+ if calls["n"] > 64:
1017
+ raise AssertionError("JOURNAL_WRITE_LOOP_UNBOUNDED: the writer accepted a zero-byte "
1018
+ "write without refusing, so the loop does not terminate")
1019
+ return 1 if calls["n"] == 1 else 0
1020
+
1021
+ class ShortDevice(Storage):
1022
+ """A device that accepts one byte and then none, through the named seam."""
1023
+
1024
+ def _write_once(self, handle, data):
1025
+ return short(handle, data)
1026
+
1027
+ return append(path, record, root=root or str(pathlib.Path(path).parent),
1028
+ storage=ShortDevice())
1029
+
1030
+
1031
+ # ---- self-test ---------------------------------------------------------------------------------
1032
+
1033
+
1034
+ def self_test():
1035
+ failures, ran = [], []
1036
+
1037
+ def control(name, got, want):
1038
+ ran.append(name)
1039
+ if want not in str(got):
1040
+ failures.append((name, f"expected {want!r} in {str(got)[:400]!r}"))
1041
+
1042
+ def clean(name, held):
1043
+ ran.append(name)
1044
+ if held:
1045
+ failures.append((name, f"expected nothing, got {held}"))
1046
+
1047
+ def refusal(call):
1048
+ try:
1049
+ call()
1050
+ except Refused as exc:
1051
+ return str(exc)
1052
+ except Exception as exc: # noqa: BLE001 - a control that dies is not a control
1053
+ return f"RAISED {type(exc).__name__}: {exc}"
1054
+ return ""
1055
+
1056
+ import shutil
1057
+ import tempfile
1058
+ # The declared root is a SUBDIRECTORY of the fixture tree, and the escape target is a sibling
1059
+ # inside the same tree. The first form used `root.parent` - which is the shared temp directory -
1060
+ # so a revert trial that removed the containment check wrote `/tmp/elsewhere.jsonl` and every
1061
+ # later run then failed the "that path has no file" control for a file no run of its own made.
1062
+ # An escape target outside the fixture tree is not a fixture.
1063
+ held_tree = pathlib.Path(tempfile.mkdtemp(prefix="jrnl-", dir="/tmp"))
1064
+ root = held_tree / "declared"
1065
+ outside = held_tree / "other" / "elsewhere.jsonl"
1066
+ root.mkdir()
1067
+ try:
1068
+ def fx_plan(**over):
1069
+ held = {"operation_id": "op-1", "target": "claude/guides/g.md",
1070
+ "before_sha256": "a" * 64, "after_sha256": "b" * 64,
1071
+ "item_id": "i-1", "approval_id": "A-0123456789abcdef"}
1072
+ held.update(over)
1073
+ return planned(**held)
1074
+
1075
+ def fx_done(**over):
1076
+ held = {"operation_id": "op-1", "target": "claude/guides/g.md",
1077
+ "before_sha256": "a" * 64, "after_sha256": "b" * 64,
1078
+ "item_id": "i-1", "approval_id": "A-0123456789abcdef", "commit": None}
1079
+ held.update(over)
1080
+ return done(**held)
1081
+
1082
+ # ---- the record ------------------------------------------------------------------------
1083
+ clean("a planned record carrying §10.5's four fields and the plan's two is accepted",
1084
+ record_problems(fx_plan()))
1085
+ clean("and a done record, which also carries its commit or null", record_problems(fx_done()))
1086
+ control("a record of neither kind is refused by name",
1087
+ "; ".join(record_problems({"kind": "started"})), "JOURNAL_KIND")
1088
+ for field in DESIGN_FIELDS + PLAN_ADDS:
1089
+ control(f"a planned record without {field} is refused by name",
1090
+ "; ".join(record_problems({k: v for k, v in fx_plan().items() if k != field})),
1091
+ f"JOURNAL_FIELD_ABSENT planned.{field}")
1092
+ control("a done record without its commit field is refused, since §10.6 reconciles a commit "
1093
+ "by that field",
1094
+ "; ".join(record_problems({k: v for k, v in fx_done().items() if k != "commit"})),
1095
+ "JOURNAL_FIELD_ABSENT done.commit")
1096
+ control("a planned record carrying a commit is refused: a commit is the effect, and there is "
1097
+ "none yet", "; ".join(record_problems({**fx_plan(), "commit": "abc"})),
1098
+ "JOURNAL_FIELD_UNDECLARED planned: commit")
1099
+ control("a field no record declares is refused rather than carried",
1100
+ "; ".join(record_problems({**fx_plan(), "note": "x"})),
1101
+ "JOURNAL_FIELD_UNDECLARED planned: note")
1102
+ control("an empty operation id is refused, since it is the durable identity §10.6 reconciles by",
1103
+ refusal(lambda: fx_plan(operation_id="")), "JOURNAL_VALUE planned.operation_id")
1104
+ clean("§10.5's own sentence names every field this module requires of it", fidelity_problems())
1105
+
1106
+ def with_sentence(sentence, call):
1107
+ """Run `call` with the design sentence replaced, restoring it however it ends."""
1108
+ global DESIGN_10_5
1109
+ kept = DESIGN_10_5
1110
+ DESIGN_10_5 = sentence
1111
+ try:
1112
+ return call()
1113
+ finally:
1114
+ DESIGN_10_5 = kept
1115
+
1116
+ control("a sentence that no longer names the before-hash is reported, so the comparison is "
1117
+ "shown to fire rather than merely to exist",
1118
+ "; ".join(with_sentence(DESIGN_10_5.replace("expected before-hash", "a hash"),
1119
+ fidelity_problems)),
1120
+ "DESIGN_FIELD_UNNAMED before_sha256")
1121
+ control("and one that no longer says the record is fsynced",
1122
+ "; ".join(with_sentence(DESIGN_10_5.replace("and fsynced", ""), fidelity_problems)),
1123
+ "DESIGN_FSYNC_UNNAMED")
1124
+ control("a phrase list covering three of the four required fields is reported, so the "
1125
+ "coverage check cannot pass over what it left out",
1126
+ "; ".join(fidelity_problems(DESIGN_PHRASES[:3])), "DESIGN_FIELD_SET")
1127
+ clean("while the list this module ships covers the required set exactly",
1128
+ [p for p in fidelity_problems() if "DESIGN_FIELD_SET" in p])
1129
+ control("and one that stops naming the `done` record",
1130
+ "; ".join(with_sentence(DESIGN_10_5.replace("a `done` record", "a second record"),
1131
+ fidelity_problems)),
1132
+ "DESIGN_KIND_UNNAMED done")
1133
+
1134
+ # ---- the framing -----------------------------------------------------------------------
1135
+ line = frame(fx_plan()).decode("utf-8")
1136
+ control("a framed line carries the payload's byte length first", line.split(" ")[0],
1137
+ str(len(json.dumps(fx_plan(), sort_keys=True, ensure_ascii=False,
1138
+ separators=(",", ":")).encode("utf-8"))))
1139
+ control("and its sha256 second", line.split(" ")[1],
1140
+ hashlib.sha256(json.dumps(fx_plan(), sort_keys=True, ensure_ascii=False,
1141
+ separators=(",", ":")).encode("utf-8")).hexdigest())
1142
+ clean("a framed line reads back as the record it framed",
1143
+ [] if _unframe(line.rstrip("\n")) == fx_plan() else [f"{_unframe(line)}"])
1144
+ clean("a payload with Korean in it survives the frame, since the length is in BYTES",
1145
+ [] if _unframe(frame({**fx_plan(), "target": "한글/안내.md"}).decode().rstrip("\n"))
1146
+ == {**fx_plan(), "target": "한글/안내.md"} else ["the Korean payload did not survive"])
1147
+ clean("a truncated payload is torn, not believed",
1148
+ [] if _unframe(line.rstrip("\n")[:-5]) is None else ["a short payload was accepted"])
1149
+ clean("a payload whose digest does not match is torn",
1150
+ [] if _unframe(line.rstrip("\n").replace('"op-1"', '"op-2"')) is None
1151
+ else ["an altered payload was accepted"])
1152
+ clean("a line with no frame at all is torn", [] if _unframe("{\"kind\": \"planned\"}") is None
1153
+ else ["an unframed line was accepted"])
1154
+
1155
+ # ---- the append ------------------------------------------------------------------------
1156
+ path = root / "state" / "journal.jsonl"
1157
+ append(path, fx_plan(), root=str(root))
1158
+ held = read(path)
1159
+ control("an appended record reads back", json.dumps(held["records"][0]), '"op-1"')
1160
+ clean("with nothing torn and no problem", held["torn"] + held["problems"])
1161
+ control("a journal outside its declared root is refused before anything is written",
1162
+ refusal(lambda: append(outside, fx_plan(), root=str(root))), "JOURNAL_OUTSIDE_ROOT")
1163
+ clean("and that path has no file", [] if not outside.exists()
1164
+ else ["a journal was written outside the root"])
1165
+ sibling = held_tree / f"{root.name}-other" / "journal.jsonl"
1166
+ control("a sibling whose NAME begins with the root's is outside it: the question is path "
1167
+ "parts, not text",
1168
+ refusal(lambda: append(sibling, fx_plan(), root=str(root))), "JOURNAL_OUTSIDE_ROOT")
1169
+ clean("and it has no file either",
1170
+ [] if not sibling.exists() else ["a journal was written into the name-prefix sibling"])
1171
+ # A symlink under the declared root: lexically inside, and the open is what refuses it.
1172
+ linked = root / "linked.jsonl"
1173
+ linked.parent.mkdir(parents=True, exist_ok=True)
1174
+ os.symlink(held_tree / "other" / "escaped.jsonl", linked)
1175
+ control("a journal path that is a SYMLINK is refused by name: the open does not follow it, "
1176
+ "which is the half a lexical containment check cannot answer",
1177
+ refusal(lambda: append(linked, fx_plan(), root=str(root))), "JOURNAL_SYMLINK")
1178
+ clean("and the file it pointed at was never created",
1179
+ [] if not (held_tree / "other" / "escaped.jsonl").exists()
1180
+ else ["the append followed the symlink"])
1181
+ # A HARD link under the declared root: no symlink, the open succeeds, the bytes are outside.
1182
+ twin_source = held_tree / "other-twin" / "outside.jsonl"
1183
+ twin_source.parent.mkdir(parents=True, exist_ok=True)
1184
+ twin_source.write_bytes(b"")
1185
+ twin = root / "twin.jsonl"
1186
+ os.link(twin_source, twin)
1187
+ control("a journal with a second name is refused before a byte is appended",
1188
+ refusal(lambda: append(twin, fx_plan(), root=str(root))), "JOURNAL_HARD_LINKED")
1189
+ clean("and the file under its other name is unchanged",
1190
+ [] if twin_source.read_bytes() == b"" else ["the append wrote through the hard link"])
1191
+ twin_source.write_bytes(b"a tail with no newline")
1192
+ control("and reconciling its torn tail is refused the same way: a truncation through this "
1193
+ "name would cut the outside file",
1194
+ refusal(lambda: reconcile_tail(twin, root=str(root))), "JOURNAL_HARD_LINKED")
1195
+ clean("and the outside file kept its bytes",
1196
+ [] if twin_source.read_bytes() == b"a tail with no newline"
1197
+ else ["the truncation cut the hard-linked file"])
1198
+ control("the writer opens with O_NOFOLLOW rather than trusting the check",
1199
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1200
+ if "flags = os.O_WRONLY" in line),
1201
+ "_NOFOLLOW")
1202
+ control("and the flag is resolved once at import, by attribute access rather than by "
1203
+ "handing the module to getattr",
1204
+ "resolved" if _NOFOLLOW else "zero on this platform", "resolved")
1205
+ control("and a short write is looped rather than acknowledged as a complete record",
1206
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1207
+ if "while written < len(data)" in line),
1208
+ "while written < len(data)")
1209
+ control("a device that stops accepting bytes mid-record is refused by name",
1210
+ refusal(lambda: _short_write_probe(root / "short.jsonl", fx_plan())),
1211
+ "JOURNAL_SHORT_WRITE")
1212
+
1213
+ # Its own symlinked root, under this control's own temp tree: a control that needs a
1214
+ # symlink builds one where it can see it, and never near the run's real roots.
1215
+ linked_root = held_tree / "linked-root"
1216
+ os.symlink(root, linked_root)
1217
+ control("a journal with no declared root at all is refused, not defaulted",
1218
+ refusal(lambda: append(path, fx_plan(), root=None)), "JOURNAL_ROOT_UNDECLARED")
1219
+ control("and a root that is a SYMLINK is refused before anything under it is reached, "
1220
+ "because a lexical check cannot see where it points",
1221
+ refusal(lambda: append(linked_root / "state" / "j.jsonl", fx_plan(),
1222
+ root=str(linked_root))),
1223
+ "JOURNAL_ROOT_UNOPENABLE")
1224
+ control("a malformed record is refused before the file is touched",
1225
+ refusal(lambda: append(root / "state" / "other.jsonl", {"kind": "planned"},
1226
+ root=str(root))),
1227
+ "JOURNAL_FIELD_ABSENT")
1228
+ clean("and that file was never created",
1229
+ [] if not (root / "state" / "other.jsonl").exists() else ["a refused record was written"])
1230
+
1231
+ # ---- the torn tail ---------------------------------------------------------------------
1232
+ torn_path = root / "state" / "torn.jsonl"
1233
+ append(torn_path, fx_plan(), root=str(root))
1234
+ with open(torn_path, "ab") as handle: # a tail cut mid-write
1235
+ handle.write(frame(fx_plan(operation_id="op-2"))[:-9])
1236
+ after = read(torn_path)
1237
+ control("a torn tail is reported as torn rather than raising",
1238
+ f'{len(after["records"])}:{len(after["torn"])}', "1:1")
1239
+ clean("and it is not a problem, because an interrupted append is what §10.6 expects",
1240
+ after["problems"])
1241
+ control("the torn line is named by its number", json.dumps(after["torn"]), '"line": 2')
1242
+ with open(torn_path, "ab") as handle: # now something after the torn line
1243
+ handle.write(b"\n")
1244
+ handle.write(frame(fx_done(operation_id="op-3")))
1245
+ middle = read(torn_path)
1246
+ control("a torn line with lines after it is corruption, named as its own problem",
1247
+ "; ".join(middle["problems"]), "JOURNAL_TORN_MIDDLE")
1248
+ control("while the records around it still read", str(len(middle["records"])), "2")
1249
+
1250
+ # ---- the seams and the lost write ------------------------------------------------------
1251
+ for seam in FAULTS:
1252
+ disarm = inject(seam)
1253
+ try:
1254
+ seam_path = root / "state" / f"seam-{seam}.jsonl"
1255
+ raised = ""
1256
+ try:
1257
+ append(seam_path, fx_plan(), root=str(root))
1258
+ except Injected as exc:
1259
+ raised = str(exc)
1260
+ control(f"the {seam} seam fires when armed", raised, seam)
1261
+ finally:
1262
+ disarm()
1263
+ # The real Storage's fsync cannot be observed from inside this process - a write is visible
1264
+ # to a reader whether or not it reached the device - so the ORDER is asserted on its source:
1265
+ # write, then the seam, then fsync, before the handle is closed. `LosingStorage` is what
1266
+ # shows the consequence of the order being wrong.
1267
+ import inspect
1268
+ storage_src = inspect.getsource(Storage.append)
1269
+ # The write is now a loop over `os.write(handle, data[written:])`, so the order is read
1270
+ # from the three operations rather than from three exact lines.
1271
+ steps = []
1272
+ for line in storage_src.splitlines():
1273
+ held_line = line.strip()
1274
+ for mark in ("self._write_once(handle,", "self._durable_file(handle,",
1275
+ "self._sync_directory(held_fd,"):
1276
+ if held_line.startswith(mark) or held_line.startswith("held = " + mark):
1277
+ steps.append(mark.rstrip("(,"))
1278
+ control("the real storage writes, then makes the file durable, then makes its whole "
1279
+ "directory chain durable, in that order", " -> ".join(steps),
1280
+ "self._write_once(handle -> self._durable_file(handle -> "
1281
+ "self._sync_directory(held_fd")
1282
+ control("and what `durable` asks the platform for is read from the platform, not assumed: "
1283
+ "on darwin plain fsync does not flush the drive's own cache, so F_FULLFSYNC is "
1284
+ "asked for where it exists",
1285
+ durable(os.open(str(root), os.O_RDONLY)),
1286
+ "F_FULLFSYNC" if hasattr(fcntl, "F_FULLFSYNC") else "fsync")
1287
+ control("a seam name the list does not hold is refused, so a misspelled seam cannot test "
1288
+ "nothing", refusal(lambda: inject("after_the_effect")), "FAULT_UNKNOWN")
1289
+ clean("and no seam stays armed after its control", sorted(_INJECTED))
1290
+
1291
+ # No effect precedes a SUCCESSFUL fsync: with the fault between the write and the fsync, the
1292
+ # record's fate is whatever the storage decides, and the TARGET shows no effect either way.
1293
+ losing = LosingStorage()
1294
+ lost_path = root / "state" / "lost.jsonl"
1295
+ disarm = inject("after_write_before_fsync")
1296
+ try:
1297
+ try:
1298
+ append(lost_path, fx_plan(), root=str(root), storage=losing)
1299
+ except Injected:
1300
+ pass
1301
+ finally:
1302
+ disarm()
1303
+ control("a fault between the write and the fsync leaves the record unsynced",
1304
+ str(len(losing.unsynced)), "1")
1305
+ control("and losing the unsynced write leaves the journal with no such record",
1306
+ f'{losing.lose_unsynced()["contents"]}:{len(read(lost_path)["records"])}',
1307
+ "1:0")
1308
+ clean("which is the state §10.5 requires: the caller had not been told the record was "
1309
+ "durable, so it had not taken its effect",
1310
+ [] if not lost_path.exists() or not read(lost_path)["records"] else ["the record survived"])
1311
+ # ---- durability of the NAMES, not only the bytes --------------------------------------
1312
+ #
1313
+ # `mkdir(parents=True)` can create a whole chain while only the journal and its immediate
1314
+ # parent are fsynced: the record is then durable inside directory entries that never
1315
+ # reached the device. The WP-21 review found it, and found that the storage fake could not
1316
+ # show it either, because it modelled contents and not entries.
1317
+ class CountingStorage(Storage):
1318
+ """A real storage that records which directories it synced, and how."""
1319
+
1320
+ def __init__(self):
1321
+ self.synced = []
1322
+ self.calls = []
1323
+
1324
+ def _sync_directory(self, held_fd, label):
1325
+ self.synced.append(str(label))
1326
+ Storage._sync_directory(self, held_fd, label)
1327
+
1328
+ def _durable_file(self, handle, label, created):
1329
+ self.calls.append(("file", str(label), created))
1330
+ Storage._durable_file(self, handle, label, created)
1331
+
1332
+ counting = CountingStorage()
1333
+ deep_path = root / "state" / "a" / "b" / "c" / "deep.jsonl"
1334
+ append(deep_path, fx_plan(), root=str(root), storage=counting)
1335
+ # The WHOLE chain, every time — including the root and including directories this append
1336
+ # found already there. A retry after a failed sync creates nothing, so a rule that synced
1337
+ # only what it created synced nothing at all and left the record durable inside entries that
1338
+ # never reached the device.
1339
+ control("the whole directory chain is synced, root included, not only what this append "
1340
+ "created",
1341
+ json.dumps(sorted(set(counting.synced))),
1342
+ json.dumps(sorted({str(root), str(root / "state"), str(root / "state" / "a"),
1343
+ str(root / "state" / "a" / "b"),
1344
+ str(root / "state" / "a" / "b" / "c")})))
1345
+ again = CountingStorage()
1346
+ # A different journal in the SAME chain: the directories are all there already, so this is
1347
+ # the retry case — nothing to create, and a created-only rule would sync nothing.
1348
+ append(deep_path.parent / "deep-again.jsonl", fx_plan(operation_id="OP-again"),
1349
+ root=str(root), storage=again)
1350
+ control("and a SECOND append into the same chain syncs it again, which is the retry the "
1351
+ "created-only rule skipped", json.dumps(sorted(set(again.synced))),
1352
+ json.dumps(sorted(set(counting.synced))))
1353
+ control("and the record is readable afterwards",
1354
+ str(len(read(deep_path)["records"])), "1")
1355
+ # The entry a device never got. `lose_names=True` is the storage whose directory sync did
1356
+ # NOT happen, which is the only state in which an entry can be lost — a directory that was
1357
+ # synced is durable, and the fake used to lose it anyway, so this control was watching the
1358
+ # fake's bookkeeping instead of the rule (the round-3 review).
1359
+ losing_dirs = LosingStorage(lose_names=True)
1360
+ lost_deep = root / "state" / "x" / "y" / "lost-deep.jsonl"
1361
+ append(lost_deep, fx_plan(), root=str(root), storage=losing_dirs)
1362
+ held_lost = losing_dirs.lose_unsynced()
1363
+ control("and the storage fake models directory ENTRIES as their own loss, which is what "
1364
+ "kept this defect invisible (the contents loss has its own control above; this one "
1365
+ "is about the names)",
1366
+ json.dumps({"directories": held_lost["directories"] > 0}),
1367
+ '{"directories": true}')
1368
+ clean("losing the entry takes the journal under it, because nothing can reach what has no "
1369
+ "name", [] if not lost_deep.exists() else ["the journal survived its own directory"])
1370
+ # And the same chain with the sync PERFORMED keeps both: the entry is not in the loss list
1371
+ # at all, so the two cases differ by the sync and not by the control's wording.
1372
+ kept_dirs = LosingStorage()
1373
+ kept_deep = root / "state" / "kept" / "deep" / "kept.jsonl"
1374
+ append(kept_deep, fx_plan(operation_id="OP-kept"), root=str(root), storage=kept_dirs)
1375
+ held_kept = kept_dirs.lose_unsynced()
1376
+ control("a chain whose directories were synced loses no entry, and the journal is still "
1377
+ "there",
1378
+ json.dumps({"directories": held_kept["directories"], "exists": kept_deep.exists()}),
1379
+ '{"directories": 0, "exists": true}')
1380
+
1381
+ # ---- the framing, on the protocol's own delimiter ------------------------------------------
1382
+ #
1383
+ # `frame` writes with ensure_ascii=False, so a payload can carry any Unicode; `read` used
1384
+ # `str.splitlines()`, which splits on U+2028, U+2029, U+0085 and more. A record whose text
1385
+ # held one of those came back as two torn lines and read as corruption. The WP-21 review
1386
+ # found it; these controls are the round trips it asked for.
1387
+ # Asked UNCONDITIONALLY. The first version of this block only ran its controls when writing
1388
+ # the record was refused, so a change that stopped refusing would have made the whole
1389
+ # framing question silently unasked — six controls that could not fire.
1390
+ for name, separator in (("line separator U+2028", "\u2028"),
1391
+ ("paragraph separator U+2029", "\u2029"),
1392
+ ("next line U+0085", "\u0085"),
1393
+ ("vertical tab", "\v"),
1394
+ ("form feed", "\f"),
1395
+ ("carriage return", "\r")):
1396
+ sep_path = root / "state" / f"sep-{ord(separator)}.jsonl"
1397
+ sep_path.parent.mkdir(parents=True, exist_ok=True)
1398
+ sep_path.write_bytes(frame({"kind": "note", "text": f"before{separator}after"}))
1399
+ held_sep = read(sep_path)
1400
+ control(f"a payload containing a {name} is one record, not two torn lines",
1401
+ f'{len(held_sep["records"])}:{len(held_sep["torn"])}', "1:0")
1402
+ control(f"and its text survives the round trip with the {name} intact",
1403
+ json.dumps((held_sep["records"] or [{}])[0].get("text")),
1404
+ json.dumps(f"before{separator}after"))
1405
+ for bad_target, want in (("claude/guides/g\u2028x.md", "JOURNAL_CONTROL_CHARACTER"),
1406
+ ("/etc/passwd", "JOURNAL_TARGET_ABSOLUTE"),
1407
+ ("~/.claude/CLAUDE.md", "JOURNAL_TARGET_ABSOLUTE"),
1408
+ ("claude/../../etc/x", "JOURNAL_TARGET_TRAVERSAL"),
1409
+ ("claude//guides/g.md", "JOURNAL_TARGET_SPELLING"),
1410
+ ("claude/guides/", "JOURNAL_TARGET_SPELLING"),
1411
+ # The spelling the two surfaces disagreed on: this suite took it
1412
+ # and `drift` refused it, so one approval was valid or invalid by
1413
+ # which surface was asked. One contract now answers both.
1414
+ ("./claude/CLAUDE.md", "JOURNAL_TARGET_SPELLING"),
1415
+ ("claude/./CLAUDE.md", "JOURNAL_TARGET_SPELLING")):
1416
+ control(f"a target spelled {bad_target!r} is refused by name",
1417
+ "; ".join(record_problems({**fx_plan(), "target": bad_target})), want)
1418
+ control("and a control character in the approval id is refused too, since every value here "
1419
+ "is written on one line",
1420
+ "; ".join(record_problems({**fx_plan(), "approval_id": "A-1\u0085x"})),
1421
+ "JOURNAL_CONTROL_CHARACTER")
1422
+ clean("while an ordinary target passes", record_problems(fx_plan()))
1423
+ control("the rule is the identity contract's, not a second copy here: the two surfaces "
1424
+ "answer one question with one answer",
1425
+ "; ".join(f"{held}|{targets.lexical_problems('./claude/CLAUDE.md')[0].split(' ')[0]}"
1426
+ for held in ["journal"]),
1427
+ "journal|TARGET_SPELLING")
1428
+
1429
+ # A control character in a record's own fields is a different question, and the record
1430
+ # rules answer it: the framing must carry any payload, and the rules decide which payloads
1431
+ # are legal records.
1432
+ control("and the append refuses such a record before writing anything",
1433
+ refusal(lambda: append(root / "state" / "ctl.jsonl",
1434
+ {**fx_plan(), "target": "claude/guides/g\u2028x.md"},
1435
+ root=str(root))),
1436
+ "JOURNAL_CONTROL_CHARACTER")
1437
+ clean("with no file left behind",
1438
+ [] if not (root / "state" / "ctl.jsonl").exists() else ["a journal was created"])
1439
+
1440
+ # A COMPLETE frame whose final newline never reached the device: torn, and appending to it
1441
+ # is refused rather than putting two records on one line.
1442
+ tail_path = root / "state" / "tail.jsonl"
1443
+ tail_path.parent.mkdir(parents=True, exist_ok=True)
1444
+ tail_path.write_bytes(frame(fx_plan()).rstrip(b"\n"))
1445
+ held_tail = read(tail_path)
1446
+ control("a frame with no trailing newline is torn, not a finished record",
1447
+ f'{len(held_tail["records"])}:{len(held_tail["torn"])}:{held_tail["unterminated"]}',
1448
+ "0:1:True")
1449
+ control("and the tear says why",
1450
+ json.dumps((held_tail["torn"] or [{}])[0].get("why")),
1451
+ '"no trailing newline"')
1452
+ control("appending to such a journal is refused by name, instead of burying the tail",
1453
+ refusal(lambda: append(tail_path, fx_plan(), root=str(root))),
1454
+ "JOURNAL_TAIL_UNRECONCILED")
1455
+ held_reconciled = reconcile_tail(tail_path, str(root))
1456
+ control("reconciling it returns what was dropped rather than discarding it silently",
1457
+ json.dumps(held_reconciled["dropped"] == frame(fx_plan()).rstrip(b"\n").decode()),
1458
+ "true")
1459
+ append(tail_path, fx_plan(), root=str(root))
1460
+ control("and then the append lands as one record on its own line",
1461
+ f'{len(read(tail_path)["records"])}:{len(read(tail_path)["torn"])}', "1:0")
1462
+ clean("reconciling a journal with a complete tail drops nothing",
1463
+ [] if reconcile_tail(tail_path, str(root))["dropped"] is None else ["it dropped a line"])
1464
+ control("and reconciling outside the declared root is refused like any other write",
1465
+ refusal(lambda: reconcile_tail(held_tree / "other" / "x.jsonl", str(root))),
1466
+ "JOURNAL_OUTSIDE_ROOT")
1467
+
1468
+ # ---- the ordering, with an effect that is actually invoked --------------------------------
1469
+ #
1470
+ # The controls above show the RECORD's fate. They say nothing about whether an effect waited
1471
+ # for it, because none of them has an effect: that was the WP-21 review's finding, and
1472
+ # `journalled` is the seam it asked for. The target here is a file inside the fixture, and
1473
+ # the before-state is held so "the effect did not happen" is a fact rather than an absence.
1474
+ effects = []
1475
+ target_file = root / "state" / "target.txt"
1476
+ target_file.parent.mkdir(parents=True, exist_ok=True)
1477
+ target_file.write_text("before\n", encoding="utf-8")
1478
+
1479
+ def take_effect():
1480
+ effects.append(target_file.read_text(encoding="utf-8"))
1481
+ target_file.write_text("after\n", encoding="utf-8")
1482
+ return "deadbeef" * 5
1483
+
1484
+ order_path = root / "state" / "ordered.jsonl"
1485
+ held_order = journalled(order_path, fx_plan(), str(root), take_effect)
1486
+ control("the effect ran, and the journal holds the plan before it did",
1487
+ f'{len(effects)}:{effects[0].strip() if effects else "never ran"}', "1:before")
1488
+ control("and the done record follows it", json.dumps(held_order["done"]["kind"]), '"done"')
1489
+ control("with the effect's own result carried into it",
1490
+ json.dumps(held_order["done"]["commit"]), '"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"')
1491
+ # compared as a LIST, here, and only the verdict handed to `control` (which looks for a substring):
1492
+ # joined with commas, `planned,done` was found inside `planned,done,planned,done` (the S11 review)
1493
+ ran.append("so the journal reads plan then done, in that order, and nothing else")
1494
+ if [row["kind"] for row in read(order_path)["records"]] != ["planned", "done"]: # equality, not a substring
1495
+ failures.append(("so the journal reads plan then done, in that order, and nothing else",
1496
+ f"got {[row['kind'] for row in read(order_path)['records']]!r}"))
1497
+ control("and the target was changed exactly once", target_file.read_text(encoding="utf-8"),
1498
+ "after")
1499
+
1500
+ # The fault case: a storage that loses the unsynced plan must leave the effect UNTAKEN.
1501
+ untaken = []
1502
+ lost_target = root / "state" / "untaken.txt"
1503
+ lost_target.write_text("before\n", encoding="utf-8")
1504
+
1505
+ class SilentStorage(Storage):
1506
+ """Returns from `append` having written nothing.
1507
+
1508
+ Not a crash and not a refusal: the shape where a storage says it is done and the device
1509
+ holds nothing. `LosingStorage` cannot model it — it writes on the way through and
1510
+ `lose_unsynced` only forgets the list — so the check that the plan is really IN the
1511
+ journal needs its own fake.
1512
+ """
1513
+
1514
+ def append(self, confined, pieces, data):
1515
+ fds, _leaf, _created = confined.walk(pieces, create=True)
1516
+ for held_fd in fds[1:]:
1517
+ os.close(held_fd)
1518
+
1519
+ said_order = refusal(lambda: journalled(
1520
+ root / "state" / "untaken.jsonl",
1521
+ fx_plan(), str(root),
1522
+ lambda: untaken.append("the effect ran") or "x",
1523
+ storage=SilentStorage()))
1524
+ control("an effect is NOT taken when the plan record did not survive the append",
1525
+ f'{said_order}|{len(untaken)}', "JOURNAL_PLAN_NOT_DURABLE")
1526
+ # And the fault BEFORE the fsync: the append raises, so `journalled` never reaches the
1527
+ # effect. The two together cover both ways the plan can fail to become durable.
1528
+ faulted = []
1529
+ disarm_order = inject("after_write_before_fsync")
1530
+ try:
1531
+ said_fault = refusal(lambda: journalled(
1532
+ root / "state" / "faulted.jsonl", fx_plan(), str(root),
1533
+ lambda: faulted.append("the effect ran") or "x", storage=LosingStorage()))
1534
+ finally:
1535
+ disarm_order()
1536
+ control("a fault between the write and the fsync stops the effect too",
1537
+ f'{said_fault}|{len(faulted)}', "Injected")
1538
+ clean("and that effect was never called either", faulted)
1539
+ clean("and the target is untouched", [] if lost_target.read_text(encoding="utf-8") == "before\n"
1540
+ else ["the effect ran anyway"])
1541
+ clean("the effect was never called at all", untaken)
1542
+
1543
+ kept = LosingStorage()
1544
+ keep_path = root / "state" / "kept.jsonl"
1545
+ append(keep_path, fx_plan(), root=str(root), storage=kept)
1546
+ control("while a completed append is synced, so losing nothing loses nothing",
1547
+ f'{kept.lose_unsynced()["contents"]}:{len(read(keep_path)["records"])}',
1548
+ "0:1")
1549
+
1550
+ # ---- what recovery reads ----------------------------------------------------------------
1551
+ many = [fx_plan(operation_id="op-a"), fx_plan(operation_id="op-b"),
1552
+ fx_done(operation_id="op-a"), fx_plan(operation_id="op-c")]
1553
+ control("every planned operation with no done is pending, in the order planned",
1554
+ ",".join(row["operation_id"] for row in pending(many)), "op-b,op-c")
1555
+ clean("a done operation is not pending", [row for row in pending(many)
1556
+ if row["operation_id"] == "op-a"])
1557
+ repeated = ",".join(row["operation_id"] for row in
1558
+ pending(many + [fx_plan(operation_id="op-b")]))
1559
+ clean("a planned record repeated is pending once, since the operation id is the identity",
1560
+ [] if repeated == "op-b,op-c" else [f"pending is {repeated!r}"])
1561
+ clean("an empty journal has nothing pending", pending([]))
1562
+ # ---- the one lock, and what it spans ----------------------------------------------------
1563
+ #
1564
+ # Its place is FIXED and declared: `journal.lock` at the top of the declared root, reached
1565
+ # through the same confined handle as the journal. The proof that it is HELD is deterministic
1566
+ # and single-process: the control opens that file itself and asks for the lock without
1567
+ # blocking, so the answer is an immediate refusal rather than a wait, and nothing is slept on
1568
+ # or killed.
1569
+ def lock_is_held(where):
1570
+ """Whether `journal.lock` under `where` is exclusively held right now."""
1571
+ held_fd = os.open(str(pathlib.Path(where) / LOCK_NAME), os.O_RDWR | os.O_CREAT, 0o600)
1572
+ try:
1573
+ fcntl.flock(held_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1574
+ fcntl.flock(held_fd, fcntl.LOCK_UN)
1575
+ return False
1576
+ except OSError:
1577
+ return True
1578
+ finally:
1579
+ os.close(held_fd)
1580
+
1581
+ control("the lock's name is fixed and declared, not a caller's choice", LOCK_NAME,
1582
+ "journal.lock")
1583
+ clean("and no lock is held when nothing is in flight",
1584
+ [] if not lock_is_held(root) else ["the lock was already held"])
1585
+ lock_path = root / LOCK_NAME
1586
+ locked_during = []
1587
+ held_lock_journal = root / "state" / "locked.jsonl"
1588
+ journalled(held_lock_journal, fx_plan(operation_id="OP-lock"), str(root),
1589
+ lambda: locked_during.append(lock_is_held(root)) or "x")
1590
+ control("the lock is held WHILE the effect runs, so nothing can append between the plan "
1591
+ "and the done record", json.dumps(locked_during), "[true]")
1592
+ clean("and it is released afterwards",
1593
+ [] if not lock_is_held(root) else ["the lock stayed held"])
1594
+ # The BOUND, deterministically: the control holds the lock itself and asks for it with a
1595
+ # wait of hundredths of a second, so the refusal arrives at once instead of in 30 s. The
1596
+ # production bound is asserted separately, as a number, because a control cannot wait it out.
1597
+ own_lock = os.open(str(lock_path), os.O_RDWR | os.O_CREAT, 0o600)
1598
+ try:
1599
+ fcntl.flock(own_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
1600
+
1601
+ def held_under_contention():
1602
+ with Confined(str(root)) as other:
1603
+ with other.lock(wait_s=0.01):
1604
+ return "took it anyway"
1605
+
1606
+ control("a lock another writer holds is refused BY NAME after its bound, not waited on "
1607
+ "without a deadline", refusal(held_under_contention), "JOURNAL_LOCKED")
1608
+ control("and the refusal names the lock file, so the reader knows what to look at",
1609
+ refusal(held_under_contention), LOCK_NAME)
1610
+ finally:
1611
+ fcntl.flock(own_lock, fcntl.LOCK_UN)
1612
+ os.close(own_lock)
1613
+ control("the production bound is 30 s and the retry is not a busy loop",
1614
+ f"{LOCK_WAIT_S:g}/{LOCK_RETRY_S:g}", "30/0.05")
1615
+ clean("and the lock is free again after the contending control let it go",
1616
+ [] if not lock_is_held(root) else ["the control kept the lock"])
1617
+ control("the lock file lives inside the root it protects",
1618
+ "inside" if destinations.inside(lock_path, root) else str(lock_path), "inside")
1619
+ control("and it is opened through the confined handle, by name under the root's own fd",
1620
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1621
+ if "os.open(LOCK_NAME" in line),
1622
+ "dir_fd=self.fd")
1623
+ for held_name, held_source in (("append", inspect.getsource(append)),
1624
+ ("journalled", inspect.getsource(journalled)),
1625
+ ("reconcile_tail", inspect.getsource(reconcile_tail))):
1626
+ control(f"{held_name} does its reading and its writing under that lock",
1627
+ "yes" if "with confined.lock():" in held_source else held_source[:200], "yes")
1628
+
1629
+ # ---- reconciliation revalidates under the lock -------------------------------------------
1630
+ #
1631
+ # It read the bytes, computed the cut, and then REOPENED the path with a plain `open` to
1632
+ # truncate. Another recovery could repair the tail and append a record in between, and the
1633
+ # truncation then cut a record made durable after the read. The cut is now measured again
1634
+ # under the lock, immediately before it is made, and unequal bytes refuse rather than cut.
1635
+ class MovingStorage(Storage):
1636
+ """A storage whose second read returns a journal that grew, as a racing writer would."""
1637
+
1638
+ def __init__(self):
1639
+ self.reads = 0
1640
+
1641
+ def read_bytes(self, confined, pieces):
1642
+ self.reads += 1
1643
+ held = Storage.read_bytes(self, confined, pieces)
1644
+ if self.reads >= 2 and held is not None:
1645
+ return held + b"another record arrived\n"
1646
+ return held
1647
+
1648
+ moving_path = root / "state" / "moving.jsonl"
1649
+ append(moving_path, fx_plan(operation_id="OP-moving"), root=str(root))
1650
+ with open(moving_path, "ab") as handle:
1651
+ handle.write(b"a torn tail with no newline")
1652
+ said_moved = refusal(lambda: reconcile_tail(moving_path, str(root), storage=MovingStorage()))
1653
+ control("a journal that moved between the read and the truncation refuses rather than "
1654
+ "cutting the length it measured earlier", said_moved,
1655
+ "JOURNAL_MOVED_UNDER_RECONCILE")
1656
+ control("and the refusal says both lengths, so the reader can see what moved", said_moved,
1657
+ "bytes then")
1658
+ clean("and the tail it would have cut is still there, because nothing was truncated",
1659
+ [] if moving_path.read_bytes().endswith(b"a torn tail with no newline")
1660
+ else ["the file was truncated anyway"])
1661
+ held_dropped = reconcile_tail(moving_path, str(root))["dropped"]
1662
+ control("while an unmoved journal reconciles, so the refusal is the race and not the "
1663
+ "mechanism", held_dropped, "a torn tail with no newline")
1664
+
1665
+ # ---- one operation id, three different situations ----------------------------------------
1666
+ #
1667
+ # `journalled` asked only whether a record with this id and kind existed, so calling it twice
1668
+ # with one id ran the effect TWICE, and an older plan under the same id satisfied the
1669
+ # durability check for a new one. Completed, conflicting and unreconciled are three answers.
1670
+ twice = []
1671
+ once_path = root / "state" / "once.jsonl"
1672
+ plan_once = fx_plan(operation_id="OP-once")
1673
+ journalled(once_path, plan_once, str(root), lambda: twice.append("ran") or "x")
1674
+ said_completed = refusal(lambda: journalled(once_path, plan_once, str(root),
1675
+ lambda: twice.append("ran again") or "x"))
1676
+ control("a COMPLETED operation is refused by its own name", said_completed,
1677
+ "JOURNAL_OPERATION_COMPLETED OP-once")
1678
+ control("and the effect did not run a second time", json.dumps(twice), '["ran"]')
1679
+ control("and it is completed ONLY: its planned row is not also read as unreconciled",
1680
+ json.dumps("JOURNAL_OPERATION_UNRECONCILED" in said_completed), "false")
1681
+ pending_path = root / "state" / "pending.jsonl"
1682
+ plan_pending = fx_plan(operation_id="OP-pending")
1683
+ append(pending_path, plan_pending, root=str(root))
1684
+ retried = []
1685
+ said_unreconciled = refusal(lambda: journalled(pending_path, plan_pending, str(root),
1686
+ lambda: retried.append("ran") or "x"))
1687
+ control("an UNRECONCILED operation is a retry, and a retry belongs to recovery",
1688
+ said_unreconciled, "JOURNAL_OPERATION_UNRECONCILED OP-pending")
1689
+ control("and the callback is not called: whether the effect happened is what the journal "
1690
+ "cannot say", json.dumps(retried), "[]")
1691
+ conflicting = []
1692
+ said_conflicting = refusal(lambda: journalled(
1693
+ pending_path, fx_plan(operation_id="OP-pending", target="claude/guides/other.md"),
1694
+ str(root), lambda: conflicting.append("ran") or "x"))
1695
+ control("a CONFLICTING plan under the same id is its own refusal, naming both digests",
1696
+ said_conflicting, "JOURNAL_OPERATION_CONFLICTING OP-pending")
1697
+ clean("and that callback does not run either", conflicting)
1698
+ control("the identity is the whole plan, so the same id with another target is another "
1699
+ "operation",
1700
+ "differs" if plan_digest(fx_plan(operation_id="OP-x")) !=
1701
+ plan_digest(fx_plan(operation_id="OP-x", target="claude/guides/z.md"))
1702
+ else "the same digest for two plans", "differs")
1703
+ control("and the kind is not part of it, so a plan and its done record speak of one "
1704
+ "operation",
1705
+ "equal" if plan_digest({**fx_plan(operation_id="OP-y"), "kind": "done"}) ==
1706
+ plan_digest(fx_plan(operation_id="OP-y")) else "the kind changed the identity",
1707
+ "equal")
1708
+
1709
+ # ---- corruption stops everything ---------------------------------------------------------
1710
+ #
1711
+ # `append` checked the torn TAIL and ignored `read`'s problems, so a journal already reported
1712
+ # as damaged in the middle took a new plan and ran an effect.
1713
+ corrupt_path = root / "state" / "corrupt.jsonl"
1714
+ append(corrupt_path, fx_plan(operation_id="OP-c1"), root=str(root))
1715
+ append(corrupt_path, fx_plan(operation_id="OP-c2"), root=str(root))
1716
+ held_lines = corrupt_path.read_bytes().split(b"\n")
1717
+ held_lines[0] = b"9999 " + b"0" * 64 + b" {\"kind\": \"planned\"}"
1718
+ corrupt_path.write_bytes(b"\n".join(held_lines))
1719
+ control("a complete line whose frame does not verify is corruption, and `read` says so",
1720
+ "; ".join(read(corrupt_path)["problems"]), "JOURNAL_TORN_MIDDLE")
1721
+ control("an append over it is refused by name rather than adding to it",
1722
+ refusal(lambda: append(corrupt_path, fx_plan(operation_id="OP-c3"),
1723
+ root=str(root))),
1724
+ "JOURNAL_CORRUPT")
1725
+ over_corruption = []
1726
+ control("and so is an effect",
1727
+ refusal(lambda: journalled(corrupt_path, fx_plan(operation_id="OP-c4"), str(root),
1728
+ lambda: over_corruption.append("ran") or "x")),
1729
+ "JOURNAL_CORRUPT")
1730
+ clean("which did not run", over_corruption)
1731
+ control("the refusal says that tail repair does not touch it, because the two recoveries "
1732
+ "are different decisions",
1733
+ refusal(lambda: append(corrupt_path, fx_plan(operation_id="OP-c5"),
1734
+ root=str(root))),
1735
+ "tail repair does not touch it")
1736
+ clean("and reconciliation leaves a corrupt middle alone: its tail is complete",
1737
+ [] if reconcile_tail(corrupt_path, str(root))["dropped"] is None
1738
+ else ["a complete line was cut"])
1739
+
1740
+ # ---- a COMPLETE line that frames nowhere -------------------------------------------------
1741
+ #
1742
+ # An append is interrupted before its newline, so the only line a tear explains is a LAST
1743
+ # line with no newline. A complete last line that framed nowhere went into `torn` with no
1744
+ # problem at all, so append and journalled ran over it: the journal said "a tear, nothing to
1745
+ # report" about bytes no append could have produced (the round-3 review).
1746
+ final_path = root / "state" / "final.jsonl"
1747
+ append(final_path, fx_plan(operation_id="OP-final"), root=str(root))
1748
+ with open(final_path, "ab") as handle:
1749
+ handle.write(b"9999 " + b"0" * 64 + b' {"kind": "planned"}\n')
1750
+ held_final = read(final_path)
1751
+ control("a complete last line whose frame does not verify is corruption, and `read` names "
1752
+ "it", "; ".join(held_final["problems"]), "JOURNAL_CORRUPT_LINE line 2")
1753
+ control("and the refusal says no interrupted append explains it",
1754
+ "; ".join(held_final["problems"]), "no interrupted append explains it")
1755
+ control("an append over it is refused rather than added to",
1756
+ refusal(lambda: append(final_path, fx_plan(operation_id="OP-f2"), root=str(root))),
1757
+ "JOURNAL_CORRUPT")
1758
+ over_final = []
1759
+ control("and so is an effect",
1760
+ refusal(lambda: journalled(final_path, fx_plan(operation_id="OP-f3"), str(root),
1761
+ lambda: over_final.append("ran") or "x")),
1762
+ "JOURNAL_CORRUPT")
1763
+ clean("which did not run", over_final)
1764
+ clean("and tail repair leaves it alone, because its newline is there",
1765
+ [] if reconcile_tail(final_path, str(root))["dropped"] is None
1766
+ else ["a complete line was cut"])
1767
+ # While an UNTERMINATED last line is still a tear, which is the case the rule must keep:
1768
+ # the two differ by the newline and by nothing else.
1769
+ tear_path = root / "state" / "tear.jsonl"
1770
+ append(tear_path, fx_plan(operation_id="OP-tear"), root=str(root))
1771
+ with open(tear_path, "ab") as handle:
1772
+ handle.write(b"an interrupted append")
1773
+ clean("an unterminated last line is a tear and carries no corruption problem",
1774
+ read(tear_path)["problems"])
1775
+ control("and tail repair removes exactly it", reconcile_tail(tear_path, str(root))["dropped"],
1776
+ "an interrupted append")
1777
+
1778
+ # The WHOLE post-append parse, before the effect. `journalled` searched the post-append
1779
+ # parse for its own plan and never read that parse's problems, so a journal this very
1780
+ # append left unparseable still carried an effect.
1781
+ class CorruptingStorage(Storage):
1782
+ """A storage whose append also writes a complete line that frames nowhere."""
1783
+
1784
+ def append(self, confined, pieces, data):
1785
+ Storage.append(self, confined, pieces, data)
1786
+ Storage.append(self, confined, pieces,
1787
+ b"9999 " + b"0" * 64 + b' {"kind": "planned"}\n')
1788
+
1789
+ after_effect = []
1790
+ control("an append that leaves the journal unparseable is refused BEFORE the effect, not "
1791
+ "after it",
1792
+ refusal(lambda: journalled(root / "state" / "after.jsonl",
1793
+ fx_plan(operation_id="OP-after"), str(root),
1794
+ lambda: after_effect.append("ran") or "x",
1795
+ storage=CorruptingStorage())),
1796
+ "the journal does not parse after the append")
1797
+ clean("and the effect did not run", after_effect)
1798
+
1799
+ # ---- a new journal's own NAME ------------------------------------------------------------
1800
+ #
1801
+ # The fake modelled contents and created directories, never the journal file's own entry, so
1802
+ # a new journal under an EXISTING directory could not be shown to disappear at all.
1803
+ (root / "state" / "existing").mkdir(parents=True, exist_ok=True)
1804
+ named_path = root / "state" / "existing" / "named.jsonl"
1805
+ losing_names = LosingStorage(lose_names=True)
1806
+ append(named_path, fx_plan(operation_id="OP-name"), root=str(root), storage=losing_names)
1807
+ control("the file is there after a file-only sync, with its record",
1808
+ str(len(read(named_path)["records"])), "1")
1809
+ held_names = losing_names.lose_unsynced()
1810
+ control("and losing the directory entry takes the file, name and all, although its contents "
1811
+ "were fsynced", json.dumps({"files": held_names["files"],
1812
+ "exists": named_path.exists()}),
1813
+ '{"files": 1, "exists": false}')
1814
+ survivor = root / "state" / "existing" / "survivor.jsonl"
1815
+ surviving = LosingStorage()
1816
+ append(survivor, fx_plan(operation_id="OP-survive"), root=str(root), storage=surviving)
1817
+ # The loss is ACTUALLY TAKEN here. The control used to read the journal without calling
1818
+ # `lose_unsynced`, so it asserted that a file written a moment ago is readable — true of any
1819
+ # write at all, and nothing about durability (the round-3 review).
1820
+ held_loss = surviving.lose_unsynced()
1821
+ control("while the same append with the directory synced survives the loss, which this "
1822
+ "control now actually takes",
1823
+ json.dumps({"records": len(read(survivor)["records"]),
1824
+ "lost": sorted((k, v) for k, v in held_loss.items()
1825
+ if k != "contents")}),
1826
+ '{"records": 1, "lost": [["directories", 0], ["files", 0]]}')
1827
+ control("and the directory that was synced is not in what the fake would lose, so the fake "
1828
+ "models the device rather than its own bookkeeping",
1829
+ json.dumps([str(p) for p in surviving.unsynced_directories]), "[]")
1830
+
1831
+ # ---- failing closed on what the platform will not give -----------------------------------
1832
+ class NoDirSync(Storage):
1833
+ """A filesystem that refuses to fsync a directory, which is a real configuration."""
1834
+
1835
+ def _dir_sync_call(self, held_fd):
1836
+ raise OSError(errno.EINVAL, "Invalid argument")
1837
+
1838
+ control("a filesystem that will not fsync a directory is refused by name, because a new "
1839
+ "journal's own name cannot be made durable there",
1840
+ refusal(lambda: append(root / "state" / "nodir.jsonl", fx_plan(),
1841
+ root=str(root), storage=NoDirSync())),
1842
+ "JOURNAL_DIRECTORY_SYNC_UNSUPPORTED")
1843
+ control("and the refusal says no durability is claimed there",
1844
+ refusal(lambda: append(root / "state" / "nodir2.jsonl", fx_plan(),
1845
+ root=str(root), storage=NoDirSync())),
1846
+ "no durability is claimed")
1847
+ # A symlink in the MIDDLE of the journal's own path, built under this control's temp tree.
1848
+ (root / "state" / "real").mkdir(parents=True, exist_ok=True)
1849
+ os.symlink(root / "state" / "real", root / "state" / "via-link")
1850
+ control("a symlinked component in the middle of the journal's path is refused, which "
1851
+ "O_NOFOLLOW on the leaf cannot catch",
1852
+ refusal(lambda: append(root / "state" / "via-link" / "j.jsonl", fx_plan(),
1853
+ root=str(root))),
1854
+ "JOURNAL_SYMLINK_COMPONENT")
1855
+ clean("and nothing was written through it",
1856
+ [] if not (root / "state" / "real" / "j.jsonl").exists()
1857
+ else ["the append followed the symlink"])
1858
+
1859
+ control("the document says how a line is framed, so a reader can check one by hand",
1860
+ document()["framing"], "sha256 of the payload")
1861
+ finally:
1862
+ shutil.rmtree(held_tree, ignore_errors=True)
1863
+
1864
+ # This module's only effect is its own append: asserted over its own AST, in both directions.
1865
+ import ast
1866
+ own = ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
1867
+ spawners = sorted({ast.unparse(node.func) for node in ast.walk(own) if isinstance(node, ast.Call)
1868
+ and ast.unparse(node.func).split(".")[0] == "subprocess"})
1869
+ clean("the journal spawns nothing: it is the record of effects, not a taker of them", spawners)
1870
+ # An EXACT set, not a containment: `", ".join(writes)` containing "os.write" was satisfied by
1871
+ # any list that happened to include it, so every call this module gained was invisible to the
1872
+ # assertion. The set is what the rule is about — these are the only ways this module touches a
1873
+ # file, and each one is inside `Storage` or `Confined` where the confinement is.
1874
+ WRITE_CALLS = ("open", "os.fsync", "os.ftruncate", "os.lstat", "os.mkdir", "os.open", "os.read",
1875
+ "os.replace", "os.stat", "os.unlink", "os.write", "shutil.rmtree")
1876
+ writes = sorted({ast.unparse(node.func) for node in ast.walk(own) if isinstance(node, ast.Call)
1877
+ and ast.unparse(node.func) in WRITE_CALLS})
1878
+ control("the calls that touch a file are exactly the ones this module declares, so a new one "
1879
+ "cannot arrive unnoticed",
1880
+ json.dumps(writes),
1881
+ json.dumps(["open", "os.fsync", "os.ftruncate", "os.lstat", "os.mkdir", "os.open",
1882
+ "os.read", "os.stat", "os.write", "shutil.rmtree"]))
1883
+ # `open` is the suite's own fixture building and `shutil.rmtree` is its teardown; the runtime
1884
+ # path uses the fd-based calls alone. Asserted, because "the suite's" is a claim about where a
1885
+ # call sits, not about its name.
1886
+ runtime_only = sorted({ast.unparse(node.func) for node in ast.walk(
1887
+ ast.Module(body=[node for node in own.body
1888
+ if not (isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
1889
+ and node.name in ("self_test", "_self_test_body"))],
1890
+ type_ignores=[]))
1891
+ if isinstance(node, ast.Call) and ast.unparse(node.func) in WRITE_CALLS})
1892
+ control("and outside the suite every one of them is reached with a `dir_fd` or an open fd — no "
1893
+ "path is opened by name there. `open` is the suite's own fixture building, and "
1894
+ "`shutil.rmtree` is `LosingStorage`'s modelled loss, which lives in this module because "
1895
+ "a fault seam belongs with the thing it tests",
1896
+ json.dumps(runtime_only),
1897
+ json.dumps(["os.fsync", "os.ftruncate", "os.lstat", "os.mkdir", "os.open", "os.read",
1898
+ "os.stat", "os.write", "shutil.rmtree"]))
1899
+ control("and `open` by name is the suite's alone", json.dumps("open" in runtime_only), "false")
1900
+
1901
+ print(f"journal --self-test: {'FAILED' if failures else 'OK'} ({len(ran)} controls: §10.5's "
1902
+ f"record fields in both kinds, the frame's length and digest against a truncated and an "
1903
+ f"altered payload, a torn tail reported and a torn middle named as corruption, the three "
1904
+ f"seams with no process killed, an unsynced write lost by a storage that drops it, and "
1905
+ f"what §10.6 reads as pending)")
1906
+ for name, detail in failures:
1907
+ print(f"journal --self-test [FAIL] {name}: {detail}")
1908
+ return 1 if failures else 0
1909
+
1910
+
1911
+ def main(argv):
1912
+ if "--self-test" in argv:
1913
+ return self_test()
1914
+ print(json.dumps(document(), indent=2, ensure_ascii=False))
1915
+ return 0
1916
+
1917
+
1918
+ if __name__ == "__main__":
1919
+ sys.exit(main(sys.argv[1:]))