fivefold 0.1.0__py3-none-any.whl

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 (128) hide show
  1. fivefold/__init__.py +4 -0
  2. fivefold/_data/db/bootstrap.sql +26 -0
  3. fivefold/_data/db/migrations/0001_schemas.sql +67 -0
  4. fivefold/_data/db/migrations/0002_gateway.sql +224 -0
  5. fivefold/_data/db/migrations/0003_gateway_record_0010.sql +91 -0
  6. fivefold/_data/db/migrations/0004_harness.sql +141 -0
  7. fivefold/_data/db/migrations/0005_sim.sql +679 -0
  8. fivefold/_data/db/migrations/0006_gateway_reads.sql +66 -0
  9. fivefold/_data/db/migrations/0007_eval.sql +33 -0
  10. fivefold/_data/db/migrations/0008_run_stop.sql +18 -0
  11. fivefold/_data/db/migrations/0009_message_copies.sql +69 -0
  12. fivefold/_data/db/migrations/0010_gateway_g1_check.sql +14 -0
  13. fivefold/_data/db/migrations/0011_model_calls.sql +37 -0
  14. fivefold/_data/db/migrations/0012_recovery_latency.sql +23 -0
  15. fivefold/_data/db/migrations/0013_split_topology.sql +33 -0
  16. fivefold/_data/db/migrations/0014_tool_call_args.sql +20 -0
  17. fivefold/_data/db/registry/0001_registry.sql +31 -0
  18. fivefold/_data/faults/expected.yaml +406 -0
  19. fivefold/_data/scenarios/dev/dev-001-single-po.yaml +45 -0
  20. fivefold/_data/scenarios/dev/dev-002-human-approval.yaml +47 -0
  21. fivefold/agents/__init__.py +7 -0
  22. fivefold/agents/branch.py +187 -0
  23. fivefold/agents/checkpoint.py +77 -0
  24. fivefold/agents/connection.py +153 -0
  25. fivefold/agents/live.py +492 -0
  26. fivefold/agents/policy.py +426 -0
  27. fivefold/agents/remote.py +333 -0
  28. fivefold/agents/replay.py +170 -0
  29. fivefold/agents/scripted.py +122 -0
  30. fivefold/agents/tools.py +229 -0
  31. fivefold/agents/worker.py +164 -0
  32. fivefold/domain/__init__.py +5 -0
  33. fivefold/domain/api.py +517 -0
  34. fivefold/domain/authority.py +149 -0
  35. fivefold/domain/contracts.py +80 -0
  36. fivefold/domain/identity.py +113 -0
  37. fivefold/domain/prices.py +178 -0
  38. fivefold/domain/report.py +92 -0
  39. fivefold/domain/rules.py +346 -0
  40. fivefold/domain/scenario.py +524 -0
  41. fivefold/evaluator/__init__.py +155 -0
  42. fivefold/evaluator/__main__.py +127 -0
  43. fivefold/evaluator/authorization.py +146 -0
  44. fivefold/evaluator/checks.py +331 -0
  45. fivefold/evaluator/evaluate.py +109 -0
  46. fivefold/evaluator/evidence.py +392 -0
  47. fivefold/evaluator/freshness.py +136 -0
  48. fivefold/evaluator/liveness.py +236 -0
  49. fivefold/evaluator/load.py +354 -0
  50. fivefold/evaluator/metrics.py +95 -0
  51. fivefold/evaluator/records.py +452 -0
  52. fivefold/evaluator/recovery.py +209 -0
  53. fivefold/evaluator/report.py +1096 -0
  54. fivefold/evaluator/result.py +344 -0
  55. fivefold/evaluator/store.py +83 -0
  56. fivefold/faults/__init__.py +5 -0
  57. fivefold/faults/catalog.py +278 -0
  58. fivefold/faults/plan.py +538 -0
  59. fivefold/gateway/__init__.py +6 -0
  60. fivefold/gateway/admin.py +179 -0
  61. fivefold/gateway/admin_api.py +398 -0
  62. fivefold/gateway/codec.py +372 -0
  63. fivefold/gateway/destination.py +64 -0
  64. fivefold/gateway/dispatcher.py +379 -0
  65. fivefold/gateway/freshness.py +83 -0
  66. fivefold/gateway/invariants.py +761 -0
  67. fivefold/gateway/memory.py +277 -0
  68. fivefold/gateway/pg_store.py +657 -0
  69. fivefold/gateway/records.py +592 -0
  70. fivefold/gateway/server.py +102 -0
  71. fivefold/gateway/sim_client.py +295 -0
  72. fivefold/gateway/state_machine.py +376 -0
  73. fivefold/gateway/steps.py +897 -0
  74. fivefold/gateway/store.py +635 -0
  75. fivefold/gateway/tools.py +424 -0
  76. fivefold/gateway/twin.py +199 -0
  77. fivefold/gateway/wire.py +138 -0
  78. fivefold/harness/__init__.py +6 -0
  79. fivefold/harness/actors.py +230 -0
  80. fivefold/harness/cells.py +303 -0
  81. fivefold/harness/clock.py +209 -0
  82. fivefold/harness/demo.py +397 -0
  83. fivefold/harness/fault_effects.py +122 -0
  84. fivefold/harness/live_options.py +159 -0
  85. fivefold/harness/log.py +540 -0
  86. fivefold/harness/mcp_link.py +409 -0
  87. fivefold/harness/migrations.py +520 -0
  88. fivefold/harness/models.py +368 -0
  89. fivefold/harness/registry.py +105 -0
  90. fivefold/harness/reports.py +100 -0
  91. fivefold/harness/rng.py +57 -0
  92. fivefold/harness/run.py +881 -0
  93. fivefold/harness/scheduler.py +441 -0
  94. fivefold/harness/sim_points.py +215 -0
  95. fivefold/harness/split/__init__.py +34 -0
  96. fivefold/harness/split/__main__.py +275 -0
  97. fivefold/harness/split/credentials.py +74 -0
  98. fivefold/harness/split/faults.py +75 -0
  99. fivefold/harness/split/gateway.py +769 -0
  100. fivefold/harness/split/hops.py +291 -0
  101. fivefold/harness/split/lifecycle.py +322 -0
  102. fivefold/harness/split/rundir.py +152 -0
  103. fivefold/harness/split/service.py +157 -0
  104. fivefold/harness/split/simulator.py +432 -0
  105. fivefold/harness/study.py +643 -0
  106. fivefold/harness/transport.py +533 -0
  107. fivefold/paths.py +24 -0
  108. fivefold/py.typed +0 -0
  109. fivefold/recorder/__init__.py +18 -0
  110. fivefold/recorder/__main__.py +308 -0
  111. fivefold/recorder/cassette.py +322 -0
  112. fivefold/recorder/playback.py +316 -0
  113. fivefold/recorder/recording.py +133 -0
  114. fivefold/sim/__init__.py +37 -0
  115. fivefold/sim/config.py +52 -0
  116. fivefold/sim/endpoint.py +176 -0
  117. fivefold/sim/ledger.py +583 -0
  118. fivefold/sim/service.py +834 -0
  119. fivefold/viewer/__init__.py +14 -0
  120. fivefold/viewer/__main__.py +75 -0
  121. fivefold/viewer/app.py +122 -0
  122. fivefold/viewer/records.py +108 -0
  123. fivefold/viewer/source.py +196 -0
  124. fivefold/viewer/timeline.py +61 -0
  125. fivefold-0.1.0.dist-info/METADATA +169 -0
  126. fivefold-0.1.0.dist-info/RECORD +128 -0
  127. fivefold-0.1.0.dist-info/WHEEL +4 -0
  128. fivefold-0.1.0.dist-info/licenses/LICENSE +202 -0
fivefold/sim/ledger.py ADDED
@@ -0,0 +1,583 @@
1
+ """Reads and writes of the `sim` schema inside one open transaction.
2
+
3
+ `Ledger` holds the SQL; `service.py` decides what to write. Every method runs in the
4
+ caller's transaction, which has already locked the run's row, so the simulator handles
5
+ one request at a time (0004). The schema checks much of what is written here
6
+ (`db/migrations/0005_sim.sql`); this module only maps rows to plain values.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass
13
+ from typing import Any, Literal, LiteralString, cast
14
+
15
+ import psycopg
16
+ from psycopg.rows import TupleRow
17
+ from psycopg.types.json import Jsonb
18
+ from pydantic import JsonValue
19
+
20
+ from fivefold.domain.authority import ApprovalStatus, Decision, approval_status_at
21
+ from fivefold.domain.rules import BUSINESS_ARGS, FactValue, Operation
22
+
23
+ Connection = psycopg.Connection[TupleRow]
24
+ Row = tuple[Any, ...]
25
+ JsonObject = dict[str, JsonValue]
26
+ Args = dict[str, str | int]
27
+
28
+ EventKind = Literal[
29
+ "setup",
30
+ "read",
31
+ "fact_changed",
32
+ "write_received",
33
+ "write_committed",
34
+ "write_replayed",
35
+ "write_in_progress",
36
+ "write_rejected",
37
+ "write_aborted",
38
+ "approval_requested",
39
+ "approval_repeated",
40
+ "approval_approved",
41
+ "approval_denied",
42
+ "approval_revoked",
43
+ "approval_status",
44
+ "status",
45
+ ]
46
+ """The kinds of `sim.event` rows."""
47
+
48
+ WriteState = Literal["received", "committed", "replayed", "in_progress", "rejected", "aborted"]
49
+ StoredStatus = Literal["pending", "approved", "denied", "revoked"]
50
+ Counter = Literal["po", "rs", "apr"]
51
+
52
+ _NEXT_NUMBER: dict[Counter, LiteralString] = {
53
+ "po": "UPDATE sim.run SET last_po_no = last_po_no + 1 RETURNING last_po_no",
54
+ "rs": "UPDATE sim.run SET last_rs_no = last_rs_no + 1 RETURNING last_rs_no",
55
+ "apr": "UPDATE sim.run SET last_apr_no = last_apr_no + 1 RETURNING last_apr_no",
56
+ }
57
+
58
+ _APPROVAL: LiteralString = (
59
+ "SELECT approval_id, intent_id, operation, scope, client_request_key, requester,"
60
+ " requested_seq, requested_vt, status, decided_seq, decided_vt, decided_by, expires_at,"
61
+ " revoked_seq, revoked_vt, revoked_by, effect_id FROM sim.approval"
62
+ )
63
+ _WRITE: LiteralString = (
64
+ "SELECT received_seq, received_vt, caller, operation, intent_id, approval_id, args, basis,"
65
+ " idempotency_key, key_honoured, client_ref, deadline_vt, deadline_waived, state,"
66
+ " outcome_seq, outcome_vt, effect_id FROM sim.write"
67
+ )
68
+ _EFFECT: LiteralString = (
69
+ "SELECT effect_id, intent_id, operation, args, approval_id, basis, idempotency_key,"
70
+ " client_ref, received_seq, commit_seq, committed_vt FROM sim.effect"
71
+ )
72
+
73
+
74
+ class LedgerError(RuntimeError):
75
+ """A row holds something the schema should have refused."""
76
+
77
+
78
+ def json_object(value: object) -> JsonObject:
79
+ """A jsonb object as loaded by psycopg."""
80
+ if not isinstance(value, dict) or not all(isinstance(key, str) for key in value):
81
+ raise LedgerError(f"expected a JSON object, found {value!r}")
82
+ return cast(JsonObject, value)
83
+
84
+
85
+ def args_of(value: object) -> Args:
86
+ """Business arguments: text or integers."""
87
+ loaded = json_object(value)
88
+ for key, item in loaded.items():
89
+ if isinstance(item, bool) or not isinstance(item, str | int):
90
+ raise LedgerError(f"argument {key} must be text or an integer, found {item!r}")
91
+ return cast(Args, loaded)
92
+
93
+
94
+ def business_args_of(operation: Operation, value: object) -> Args:
95
+ """An operation's business arguments, in record 0001's order."""
96
+ loaded = args_of(value)
97
+ names = BUSINESS_ARGS[operation]
98
+ if set(loaded) != set(names):
99
+ raise LedgerError(f"{operation} takes the arguments {names}, not {sorted(loaded)}")
100
+ return {name: loaded[name] for name in names}
101
+
102
+
103
+ def basis_of(value: object) -> dict[str, int]:
104
+ """A basis: fact key to version."""
105
+ loaded = json_object(value)
106
+ for key, item in loaded.items():
107
+ if isinstance(item, bool) or not isinstance(item, int):
108
+ raise LedgerError(f"the version of {key} must be an integer, found {item!r}")
109
+ return cast(dict[str, int], loaded)
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class ApprovalRow:
114
+ """One row of `sim.approval`."""
115
+
116
+ approval_id: str
117
+ intent_id: str
118
+ operation: Operation
119
+ scope: Args
120
+ client_request_key: str | None
121
+ requester: str
122
+ requested_seq: int
123
+ requested_vt: int
124
+ status: StoredStatus
125
+ decided_seq: int | None
126
+ decided_vt: int | None
127
+ decided_by: str | None
128
+ expires_at: int | None
129
+ revoked_seq: int | None
130
+ revoked_vt: int | None
131
+ revoked_by: str | None
132
+ effect_id: str | None
133
+
134
+ def status_at(self, vt: int) -> ApprovalStatus:
135
+ """The status the approvals service reports at `vt` (0002, rules 8 and 9)."""
136
+ decision = None
137
+ if self.status in ("approved", "revoked"):
138
+ decision = Decision.APPROVE
139
+ elif self.status == "denied":
140
+ decision = Decision.DENY
141
+ return approval_status_at(
142
+ decision=decision,
143
+ revoked=self.status == "revoked",
144
+ expires_at=self.expires_at,
145
+ vt=vt,
146
+ )
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class WriteRow:
151
+ """One row of `sim.write`."""
152
+
153
+ received_seq: int
154
+ received_vt: int
155
+ caller: str
156
+ operation: Operation
157
+ intent_id: str
158
+ approval_id: str
159
+ args: Args
160
+ basis: dict[str, int]
161
+ idempotency_key: str | None
162
+ key_honoured: bool
163
+ client_ref: str | None
164
+ deadline_vt: int
165
+ deadline_waived: bool
166
+ state: WriteState
167
+ outcome_seq: int | None
168
+ outcome_vt: int | None
169
+ effect_id: str | None
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class NewWrite:
174
+ """What a write request asks for, as it reaches the destination."""
175
+
176
+ received_seq: int
177
+ caller: str
178
+ operation: Operation
179
+ intent_id: str
180
+ approval_id: str
181
+ args: Args
182
+ basis: dict[str, int]
183
+ idempotency_key: str | None
184
+ key_honoured: bool
185
+ client_ref: str | None
186
+ deadline_vt: int
187
+ deadline_waived: bool
188
+
189
+
190
+ @dataclass(frozen=True)
191
+ class EffectRow:
192
+ """One row of `sim.effect`."""
193
+
194
+ effect_id: str
195
+ intent_id: str
196
+ operation: Operation
197
+ args: Args
198
+ approval_id: str
199
+ basis: dict[str, int]
200
+ idempotency_key: str | None
201
+ client_ref: str | None
202
+ received_seq: int
203
+ commit_seq: int
204
+ committed_vt: int
205
+
206
+
207
+ def _approval(row: Row) -> ApprovalRow:
208
+ return ApprovalRow(
209
+ approval_id=str(row[0]),
210
+ intent_id=str(row[1]),
211
+ operation=Operation(row[2]),
212
+ scope=args_of(row[3]),
213
+ client_request_key=row[4],
214
+ requester=str(row[5]),
215
+ requested_seq=int(row[6]),
216
+ requested_vt=int(row[7]),
217
+ status=cast(StoredStatus, str(row[8])),
218
+ decided_seq=row[9],
219
+ decided_vt=row[10],
220
+ decided_by=row[11],
221
+ expires_at=row[12],
222
+ revoked_seq=row[13],
223
+ revoked_vt=row[14],
224
+ revoked_by=row[15],
225
+ effect_id=row[16],
226
+ )
227
+
228
+
229
+ def _write(row: Row) -> WriteRow:
230
+ return WriteRow(
231
+ received_seq=int(row[0]),
232
+ received_vt=int(row[1]),
233
+ caller=str(row[2]),
234
+ operation=Operation(row[3]),
235
+ intent_id=str(row[4]),
236
+ approval_id=str(row[5]),
237
+ args=business_args_of(Operation(row[3]), row[6]),
238
+ basis=basis_of(row[7]),
239
+ idempotency_key=row[8],
240
+ key_honoured=bool(row[9]),
241
+ client_ref=row[10],
242
+ deadline_vt=int(row[11]),
243
+ deadline_waived=bool(row[12]),
244
+ state=cast(WriteState, str(row[13])),
245
+ outcome_seq=row[14],
246
+ outcome_vt=row[15],
247
+ effect_id=row[16],
248
+ )
249
+
250
+
251
+ def _effect(row: Row) -> EffectRow:
252
+ return EffectRow(
253
+ effect_id=str(row[0]),
254
+ intent_id=str(row[1]),
255
+ operation=Operation(row[2]),
256
+ args=business_args_of(Operation(row[2]), row[3]),
257
+ approval_id=str(row[4]),
258
+ basis=basis_of(row[5]),
259
+ idempotency_key=row[6],
260
+ client_ref=row[7],
261
+ received_seq=int(row[8]),
262
+ commit_seq=int(row[9]),
263
+ committed_vt=int(row[10]),
264
+ )
265
+
266
+
267
+ class Ledger:
268
+ """The `sim` tables, inside one open transaction at virtual time `vt`."""
269
+
270
+ def __init__(self, conn: Connection, vt: int) -> None:
271
+ self._conn = conn
272
+ self.vt = vt
273
+ self.aborted: list[int] = []
274
+ """Writes this transaction aborted for missing their deadline, by received seq."""
275
+
276
+ def _one(self, query: LiteralString, params: tuple[object, ...]) -> Row:
277
+ row = self._conn.execute(query, params).fetchone()
278
+ if row is None:
279
+ raise LedgerError(f"no row for: {query}")
280
+ return row
281
+
282
+ # Events and counters ---------------------------------------------------------------
283
+
284
+ def event(self, kind: EventKind, actor: str, ref: str | None) -> int:
285
+ """Record an event at this transaction's time and return its seq."""
286
+ row = self._one(
287
+ "INSERT INTO sim.event (vt, kind, actor, ref) VALUES (%s, %s, %s, %s) RETURNING seq",
288
+ (self.vt, kind, actor, ref),
289
+ )
290
+ return int(row[0])
291
+
292
+ def next_number(self, counter: Counter) -> int:
293
+ """The next number of a per-run id counter: PO-, RS- or APR-."""
294
+ return int(self._one(_NEXT_NUMBER[counter], ())[0])
295
+
296
+ # Facts -----------------------------------------------------------------------------
297
+
298
+ def latest_fact(self, key: str) -> tuple[int, JsonObject] | None:
299
+ """The latest version of a fact and its value, or None if there is no such fact."""
300
+ row = self._conn.execute(
301
+ "SELECT version, value FROM sim.fact_version WHERE key = %s"
302
+ " ORDER BY version DESC LIMIT 1",
303
+ (key,),
304
+ ).fetchone()
305
+ return None if row is None else (int(row[0]), json_object(row[1]))
306
+
307
+ def fact_at(self, key: str, version: int) -> JsonObject | None:
308
+ """A fact's value at one version, or None if that version does not exist."""
309
+ row = self._conn.execute(
310
+ "SELECT value FROM sim.fact_version WHERE key = %s AND version = %s", (key, version)
311
+ ).fetchone()
312
+ return None if row is None else json_object(row[0])
313
+
314
+ def add_fact_version(
315
+ self,
316
+ key: str,
317
+ version: int,
318
+ value: Mapping[str, object],
319
+ seq: int,
320
+ *,
321
+ cause: Literal["initial", "effect", "control"],
322
+ effect_id: str | None = None,
323
+ actor: str | None = None,
324
+ ) -> None:
325
+ """Append a version of a fact, valid from event `seq`."""
326
+ self._conn.execute(
327
+ "INSERT INTO sim.fact_version (key, version, value, valid_from_seq, valid_from_vt,"
328
+ " cause, cause_effect_id, cause_actor) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
329
+ (key, version, Jsonb(dict(value)), seq, self.vt, cause, effect_id, actor),
330
+ )
331
+
332
+ def log_read(self, seq: int, key: str, version: int, caller: str) -> None:
333
+ """Record a read served at event `seq`."""
334
+ self._conn.execute(
335
+ "INSERT INTO sim.read_log (seq, key, version, caller, vt) VALUES (%s, %s, %s, %s, %s)",
336
+ (seq, key, version, caller, self.vt),
337
+ )
338
+
339
+ def served_before(self, key: str, version: int, seq: int) -> bool:
340
+ """Whether this version of the fact was served to the run before event `seq`."""
341
+ row = self._one(
342
+ "SELECT EXISTS (SELECT 1 FROM sim.read_log WHERE key = %s AND version = %s"
343
+ " AND seq < %s)",
344
+ (key, version, seq),
345
+ )
346
+ return bool(row[0])
347
+
348
+ # Approvals -------------------------------------------------------------------------
349
+
350
+ def approval(self, approval_id: str) -> ApprovalRow | None:
351
+ """One approval, or None."""
352
+ row = self._conn.execute(_APPROVAL + " WHERE approval_id = %s", (approval_id,)).fetchone()
353
+ return None if row is None else _approval(row)
354
+
355
+ def approval_by_request_key(self, client_request_key: str) -> ApprovalRow | None:
356
+ """The approval filed with this client request key, or None."""
357
+ row = self._conn.execute(
358
+ _APPROVAL + " WHERE client_request_key = %s", (client_request_key,)
359
+ ).fetchone()
360
+ return None if row is None else _approval(row)
361
+
362
+ def pending_approvals(self) -> list[ApprovalRow]:
363
+ """Approvals waiting for a decision, in the order they were requested."""
364
+ rows = self._conn.execute(
365
+ _APPROVAL + " WHERE status = 'pending' ORDER BY requested_seq"
366
+ ).fetchall()
367
+ return [_approval(row) for row in rows]
368
+
369
+ def insert_approval(
370
+ self,
371
+ approval_id: str,
372
+ *,
373
+ intent_id: str,
374
+ operation: Operation,
375
+ scope: Mapping[str, object],
376
+ client_request_key: str | None,
377
+ requester: str,
378
+ requested_seq: int,
379
+ ) -> None:
380
+ """File a pending approval request."""
381
+ self._conn.execute(
382
+ "INSERT INTO sim.approval (approval_id, intent_id, operation, scope,"
383
+ " client_request_key, requester, requested_seq, requested_vt, status)"
384
+ " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'pending')",
385
+ (
386
+ approval_id,
387
+ intent_id,
388
+ str(operation),
389
+ Jsonb(dict(scope)),
390
+ client_request_key,
391
+ requester,
392
+ requested_seq,
393
+ self.vt,
394
+ ),
395
+ )
396
+
397
+ def add_approval_event(
398
+ self,
399
+ seq: int,
400
+ approval_id: str,
401
+ kind: Literal["requested", "approved", "denied", "revoked"],
402
+ actor: str,
403
+ ) -> None:
404
+ """Append an approval event at event `seq`."""
405
+ self._conn.execute(
406
+ "INSERT INTO sim.approval_event (seq, approval_id, kind, actor, vt)"
407
+ " VALUES (%s, %s, %s, %s, %s)",
408
+ (seq, approval_id, kind, actor, self.vt),
409
+ )
410
+
411
+ def set_decision(
412
+ self,
413
+ approval_id: str,
414
+ status: Literal["approved", "denied"],
415
+ *,
416
+ seq: int,
417
+ actor: str,
418
+ expires_at: int | None,
419
+ ) -> None:
420
+ """Record a decision on a pending approval."""
421
+ self._conn.execute(
422
+ "UPDATE sim.approval SET status = %s, decided_seq = %s, decided_vt = %s,"
423
+ " decided_by = %s, expires_at = %s WHERE approval_id = %s",
424
+ (status, seq, self.vt, actor, expires_at, approval_id),
425
+ )
426
+
427
+ def set_revocation(self, approval_id: str, *, seq: int, actor: str) -> None:
428
+ """Record the revocation of an approved approval."""
429
+ self._conn.execute(
430
+ "UPDATE sim.approval SET status = 'revoked', revoked_seq = %s, revoked_vt = %s,"
431
+ " revoked_by = %s WHERE approval_id = %s",
432
+ (seq, self.vt, actor, approval_id),
433
+ )
434
+
435
+ def set_backed_effect(self, approval_id: str, effect_id: str) -> None:
436
+ """Record the effect an approval backs: the first that cites it (0002, rule 10)."""
437
+ self._conn.execute(
438
+ "UPDATE sim.approval SET effect_id = %s WHERE approval_id = %s",
439
+ (effect_id, approval_id),
440
+ )
441
+
442
+ # Writes and effects ----------------------------------------------------------------
443
+
444
+ def write(self, received_seq: int) -> WriteRow | None:
445
+ """One write request, or None."""
446
+ row = self._conn.execute(_WRITE + " WHERE received_seq = %s", (received_seq,)).fetchone()
447
+ return None if row is None else _write(row)
448
+
449
+ def insert_write(
450
+ self,
451
+ write: NewWrite,
452
+ *,
453
+ state: WriteState = "received",
454
+ outcome_seq: int | None = None,
455
+ effect_id: str | None = None,
456
+ ) -> None:
457
+ """Record a write request that reached the destination, with its outcome if decided.
458
+
459
+ Only a replay or `in_progress` is decided on arrival; anything else is in flight.
460
+ """
461
+ self._conn.execute(
462
+ "INSERT INTO sim.write (received_seq, received_vt, caller, operation, intent_id,"
463
+ " approval_id, args, basis, idempotency_key, key_honoured, client_ref, deadline_vt,"
464
+ " deadline_waived, state, outcome_seq, outcome_vt, effect_id)"
465
+ " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
466
+ (
467
+ write.received_seq,
468
+ self.vt,
469
+ write.caller,
470
+ str(write.operation),
471
+ write.intent_id,
472
+ write.approval_id,
473
+ Jsonb(dict(write.args)),
474
+ Jsonb(dict(write.basis)),
475
+ write.idempotency_key,
476
+ write.key_honoured,
477
+ write.client_ref,
478
+ write.deadline_vt,
479
+ write.deadline_waived,
480
+ state,
481
+ outcome_seq,
482
+ None if outcome_seq is None else self.vt,
483
+ effect_id,
484
+ ),
485
+ )
486
+
487
+ def set_write_outcome(
488
+ self,
489
+ received_seq: int,
490
+ state: WriteState,
491
+ *,
492
+ outcome_seq: int,
493
+ effect_id: str | None = None,
494
+ rejection: Mapping[str, object] | None = None,
495
+ ) -> None:
496
+ """Record the outcome of a write that was in flight."""
497
+ self._conn.execute(
498
+ "UPDATE sim.write SET state = %s, outcome_seq = %s, outcome_vt = %s, effect_id = %s,"
499
+ " rejection = %s WHERE received_seq = %s",
500
+ (
501
+ state,
502
+ outcome_seq,
503
+ self.vt,
504
+ effect_id,
505
+ None if rejection is None else Jsonb(dict(rejection)),
506
+ received_seq,
507
+ ),
508
+ )
509
+
510
+ def key_in_flight(self, idempotency_key: str) -> bool:
511
+ """Whether a write with this honoured key is in flight."""
512
+ row = self._one(
513
+ "SELECT EXISTS (SELECT 1 FROM sim.write WHERE idempotency_key = %s"
514
+ " AND key_honoured AND state = 'received')",
515
+ (idempotency_key,),
516
+ )
517
+ return bool(row[0])
518
+
519
+ def overdue_writes(self) -> list[WriteRow]:
520
+ """Writes in flight past their deadline, unless a fault waived it, oldest first."""
521
+ rows = self._conn.execute(
522
+ _WRITE + " WHERE state = 'received' AND NOT deadline_waived AND deadline_vt < %s"
523
+ " ORDER BY received_seq",
524
+ (self.vt,),
525
+ ).fetchall()
526
+ return [_write(row) for row in rows]
527
+
528
+ def effect_by_key(self, idempotency_key: str) -> EffectRow | None:
529
+ """The effect that stored this idempotency key, or None."""
530
+ row = self._conn.execute(
531
+ _EFFECT + " WHERE idempotency_key = %s", (idempotency_key,)
532
+ ).fetchone()
533
+ return None if row is None else _effect(row)
534
+
535
+ def effects_for(self, intent_id: str, operation: Operation, up_to_vt: int) -> list[EffectRow]:
536
+ """Effects of one intent and operation committed at or before `up_to_vt`."""
537
+ rows = self._conn.execute(
538
+ _EFFECT + " WHERE intent_id = %s AND operation = %s AND committed_vt <= %s"
539
+ " ORDER BY commit_seq",
540
+ (intent_id, str(operation), up_to_vt),
541
+ ).fetchall()
542
+ return [_effect(row) for row in rows]
543
+
544
+ def insert_effect(self, effect_id: str, write: WriteRow, *, commit_seq: int) -> None:
545
+ """Record an effect that commits `write` at event `commit_seq`."""
546
+ self._conn.execute(
547
+ "INSERT INTO sim.effect (effect_id, intent_id, operation, args, approval_id, basis,"
548
+ " idempotency_key, client_ref, received_seq, commit_seq, committed_vt)"
549
+ " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
550
+ (
551
+ effect_id,
552
+ write.intent_id,
553
+ str(write.operation),
554
+ Jsonb(dict(write.args)),
555
+ write.approval_id,
556
+ Jsonb(dict(write.basis)),
557
+ write.idempotency_key if write.key_honoured else None,
558
+ write.client_ref,
559
+ write.received_seq,
560
+ commit_seq,
561
+ self.vt,
562
+ ),
563
+ )
564
+
565
+
566
+ class History:
567
+ """The facts as a basis check at commit reads them (`rules.FactHistory`).
568
+
569
+ Reads count only if served before the write reached the simulator (0004, property 3).
570
+ """
571
+
572
+ def __init__(self, ledger: Ledger, received_seq: int) -> None:
573
+ self._ledger = ledger
574
+ self._received_seq = received_seq
575
+
576
+ def value_at(self, key: str, version: int) -> FactValue | None:
577
+ return self._ledger.fact_at(key, version)
578
+
579
+ def current(self, key: str) -> tuple[int, FactValue] | None:
580
+ return self._ledger.latest_fact(key)
581
+
582
+ def was_served(self, key: str, version: int) -> bool:
583
+ return self._ledger.served_before(key, version, self._received_seq)