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.
- fivefold/__init__.py +4 -0
- fivefold/_data/db/bootstrap.sql +26 -0
- fivefold/_data/db/migrations/0001_schemas.sql +67 -0
- fivefold/_data/db/migrations/0002_gateway.sql +224 -0
- fivefold/_data/db/migrations/0003_gateway_record_0010.sql +91 -0
- fivefold/_data/db/migrations/0004_harness.sql +141 -0
- fivefold/_data/db/migrations/0005_sim.sql +679 -0
- fivefold/_data/db/migrations/0006_gateway_reads.sql +66 -0
- fivefold/_data/db/migrations/0007_eval.sql +33 -0
- fivefold/_data/db/migrations/0008_run_stop.sql +18 -0
- fivefold/_data/db/migrations/0009_message_copies.sql +69 -0
- fivefold/_data/db/migrations/0010_gateway_g1_check.sql +14 -0
- fivefold/_data/db/migrations/0011_model_calls.sql +37 -0
- fivefold/_data/db/migrations/0012_recovery_latency.sql +23 -0
- fivefold/_data/db/migrations/0013_split_topology.sql +33 -0
- fivefold/_data/db/migrations/0014_tool_call_args.sql +20 -0
- fivefold/_data/db/registry/0001_registry.sql +31 -0
- fivefold/_data/faults/expected.yaml +406 -0
- fivefold/_data/scenarios/dev/dev-001-single-po.yaml +45 -0
- fivefold/_data/scenarios/dev/dev-002-human-approval.yaml +47 -0
- fivefold/agents/__init__.py +7 -0
- fivefold/agents/branch.py +187 -0
- fivefold/agents/checkpoint.py +77 -0
- fivefold/agents/connection.py +153 -0
- fivefold/agents/live.py +492 -0
- fivefold/agents/policy.py +426 -0
- fivefold/agents/remote.py +333 -0
- fivefold/agents/replay.py +170 -0
- fivefold/agents/scripted.py +122 -0
- fivefold/agents/tools.py +229 -0
- fivefold/agents/worker.py +164 -0
- fivefold/domain/__init__.py +5 -0
- fivefold/domain/api.py +517 -0
- fivefold/domain/authority.py +149 -0
- fivefold/domain/contracts.py +80 -0
- fivefold/domain/identity.py +113 -0
- fivefold/domain/prices.py +178 -0
- fivefold/domain/report.py +92 -0
- fivefold/domain/rules.py +346 -0
- fivefold/domain/scenario.py +524 -0
- fivefold/evaluator/__init__.py +155 -0
- fivefold/evaluator/__main__.py +127 -0
- fivefold/evaluator/authorization.py +146 -0
- fivefold/evaluator/checks.py +331 -0
- fivefold/evaluator/evaluate.py +109 -0
- fivefold/evaluator/evidence.py +392 -0
- fivefold/evaluator/freshness.py +136 -0
- fivefold/evaluator/liveness.py +236 -0
- fivefold/evaluator/load.py +354 -0
- fivefold/evaluator/metrics.py +95 -0
- fivefold/evaluator/records.py +452 -0
- fivefold/evaluator/recovery.py +209 -0
- fivefold/evaluator/report.py +1096 -0
- fivefold/evaluator/result.py +344 -0
- fivefold/evaluator/store.py +83 -0
- fivefold/faults/__init__.py +5 -0
- fivefold/faults/catalog.py +278 -0
- fivefold/faults/plan.py +538 -0
- fivefold/gateway/__init__.py +6 -0
- fivefold/gateway/admin.py +179 -0
- fivefold/gateway/admin_api.py +398 -0
- fivefold/gateway/codec.py +372 -0
- fivefold/gateway/destination.py +64 -0
- fivefold/gateway/dispatcher.py +379 -0
- fivefold/gateway/freshness.py +83 -0
- fivefold/gateway/invariants.py +761 -0
- fivefold/gateway/memory.py +277 -0
- fivefold/gateway/pg_store.py +657 -0
- fivefold/gateway/records.py +592 -0
- fivefold/gateway/server.py +102 -0
- fivefold/gateway/sim_client.py +295 -0
- fivefold/gateway/state_machine.py +376 -0
- fivefold/gateway/steps.py +897 -0
- fivefold/gateway/store.py +635 -0
- fivefold/gateway/tools.py +424 -0
- fivefold/gateway/twin.py +199 -0
- fivefold/gateway/wire.py +138 -0
- fivefold/harness/__init__.py +6 -0
- fivefold/harness/actors.py +230 -0
- fivefold/harness/cells.py +303 -0
- fivefold/harness/clock.py +209 -0
- fivefold/harness/demo.py +397 -0
- fivefold/harness/fault_effects.py +122 -0
- fivefold/harness/live_options.py +159 -0
- fivefold/harness/log.py +540 -0
- fivefold/harness/mcp_link.py +409 -0
- fivefold/harness/migrations.py +520 -0
- fivefold/harness/models.py +368 -0
- fivefold/harness/registry.py +105 -0
- fivefold/harness/reports.py +100 -0
- fivefold/harness/rng.py +57 -0
- fivefold/harness/run.py +881 -0
- fivefold/harness/scheduler.py +441 -0
- fivefold/harness/sim_points.py +215 -0
- fivefold/harness/split/__init__.py +34 -0
- fivefold/harness/split/__main__.py +275 -0
- fivefold/harness/split/credentials.py +74 -0
- fivefold/harness/split/faults.py +75 -0
- fivefold/harness/split/gateway.py +769 -0
- fivefold/harness/split/hops.py +291 -0
- fivefold/harness/split/lifecycle.py +322 -0
- fivefold/harness/split/rundir.py +152 -0
- fivefold/harness/split/service.py +157 -0
- fivefold/harness/split/simulator.py +432 -0
- fivefold/harness/study.py +643 -0
- fivefold/harness/transport.py +533 -0
- fivefold/paths.py +24 -0
- fivefold/py.typed +0 -0
- fivefold/recorder/__init__.py +18 -0
- fivefold/recorder/__main__.py +308 -0
- fivefold/recorder/cassette.py +322 -0
- fivefold/recorder/playback.py +316 -0
- fivefold/recorder/recording.py +133 -0
- fivefold/sim/__init__.py +37 -0
- fivefold/sim/config.py +52 -0
- fivefold/sim/endpoint.py +176 -0
- fivefold/sim/ledger.py +583 -0
- fivefold/sim/service.py +834 -0
- fivefold/viewer/__init__.py +14 -0
- fivefold/viewer/__main__.py +75 -0
- fivefold/viewer/app.py +122 -0
- fivefold/viewer/records.py +108 -0
- fivefold/viewer/source.py +196 -0
- fivefold/viewer/timeline.py +61 -0
- fivefold-0.1.0.dist-info/METADATA +169 -0
- fivefold-0.1.0.dist-info/RECORD +128 -0
- fivefold-0.1.0.dist-info/WHEEL +4 -0
- fivefold-0.1.0.dist-info/licenses/LICENSE +202 -0
fivefold/sim/service.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
1
|
+
"""The procurement simulator: reads, approvals, writes and status (0002, 0004, 0005).
|
|
2
|
+
|
|
3
|
+
`Simulator` serves one run. It connects as `ff_sim`, the only role that writes the `sim`
|
|
4
|
+
schema (0008). Every call takes the virtual time `vt` and, for API calls, the caller's
|
|
5
|
+
identity. It never reads a clock or a random source (0009). Each call is one database
|
|
6
|
+
transaction that first locks the run's row, so the simulator handles one request at a
|
|
7
|
+
time and one gap-free sequence orders its events (0004). Nothing here waits: a caller
|
|
8
|
+
that wants to wait, such as B0's `get_approval_status(wait_ms)`, waits in the harness on
|
|
9
|
+
virtual-time timers.
|
|
10
|
+
|
|
11
|
+
Every call starts by aborting the writes in flight whose commit deadline has passed
|
|
12
|
+
(0005). The harness's split path, `receive_write` then `commit_received`, lets a fault
|
|
13
|
+
delay a commit (F5). `Control` is the harness's interface for scripted humans and fault
|
|
14
|
+
plans: decide, revoke, change a fact.
|
|
15
|
+
|
|
16
|
+
Use a simulator from one thread at a time, as the deterministic scheduler does (0009).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from collections.abc import Iterator, Mapping
|
|
22
|
+
from contextlib import contextmanager
|
|
23
|
+
from types import TracebackType
|
|
24
|
+
|
|
25
|
+
import psycopg
|
|
26
|
+
from psycopg.types.json import Jsonb
|
|
27
|
+
from pydantic import JsonValue, ValidationError
|
|
28
|
+
|
|
29
|
+
from fivefold.domain.api import (
|
|
30
|
+
SCOPE_MODELS,
|
|
31
|
+
ApprovalAnswer,
|
|
32
|
+
CheckName,
|
|
33
|
+
FactRead,
|
|
34
|
+
FailedCheck,
|
|
35
|
+
GetApprovalStatus,
|
|
36
|
+
GetBudget,
|
|
37
|
+
GetInventory,
|
|
38
|
+
GetOrderStatus,
|
|
39
|
+
GetQuote,
|
|
40
|
+
GetReservationStatus,
|
|
41
|
+
ListSuppliers,
|
|
42
|
+
Refusal,
|
|
43
|
+
RefusalReason,
|
|
44
|
+
RequestApproval,
|
|
45
|
+
ReserveInventory,
|
|
46
|
+
StatusAnswer,
|
|
47
|
+
StatusEffect,
|
|
48
|
+
SubmitPurchaseOrder,
|
|
49
|
+
Write,
|
|
50
|
+
WriteAborted,
|
|
51
|
+
WriteAnswer,
|
|
52
|
+
WriteCommitted,
|
|
53
|
+
WriteInProgress,
|
|
54
|
+
WriteReceived,
|
|
55
|
+
WriteRejected,
|
|
56
|
+
WriteRejectReason,
|
|
57
|
+
)
|
|
58
|
+
from fivefold.domain.authority import (
|
|
59
|
+
POLICY_ACTOR,
|
|
60
|
+
ApprovalStatus,
|
|
61
|
+
Decision,
|
|
62
|
+
PolicyDecision,
|
|
63
|
+
scope_mismatches,
|
|
64
|
+
)
|
|
65
|
+
from fivefold.domain.contracts import Capability, ContractParams
|
|
66
|
+
from fivefold.domain.rules import (
|
|
67
|
+
SUPPLIERS_KEY,
|
|
68
|
+
FactKind,
|
|
69
|
+
Operation,
|
|
70
|
+
budget_key,
|
|
71
|
+
check_basis,
|
|
72
|
+
consequence,
|
|
73
|
+
consequence_key,
|
|
74
|
+
fact_kind,
|
|
75
|
+
inventory_key,
|
|
76
|
+
quote_key,
|
|
77
|
+
)
|
|
78
|
+
from fivefold.domain.scenario import FACT_MODELS, Authority, Scenario
|
|
79
|
+
from fivefold.sim.config import SimConfig
|
|
80
|
+
from fivefold.sim.ledger import (
|
|
81
|
+
ApprovalRow,
|
|
82
|
+
Connection,
|
|
83
|
+
EffectRow,
|
|
84
|
+
History,
|
|
85
|
+
JsonObject,
|
|
86
|
+
Ledger,
|
|
87
|
+
NewWrite,
|
|
88
|
+
WriteRow,
|
|
89
|
+
json_object,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
SIM_ROLE = "ff_sim"
|
|
93
|
+
"""The database role the simulator connects as (0008)."""
|
|
94
|
+
|
|
95
|
+
SIM_ACTOR = "simulator"
|
|
96
|
+
"""The actor of events the simulator causes itself: setup and deadline aborts."""
|
|
97
|
+
|
|
98
|
+
_STATUS_CHECKS: Mapping[ApprovalStatus, CheckName] = {
|
|
99
|
+
ApprovalStatus.PENDING: CheckName.APPROVAL_PENDING,
|
|
100
|
+
ApprovalStatus.DENIED: CheckName.APPROVAL_DENIED,
|
|
101
|
+
ApprovalStatus.REVOKED: CheckName.APPROVAL_REVOKED,
|
|
102
|
+
ApprovalStatus.EXPIRED: CheckName.APPROVAL_EXPIRED,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class SimulatorError(Exception):
|
|
107
|
+
"""The simulator was used in a way the run does not allow."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class WrongRole(SimulatorError):
|
|
111
|
+
"""The connection's role is not `ff_sim`."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class NotSetUp(SimulatorError):
|
|
115
|
+
"""The run database has no simulator run yet."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class AlreadySetUp(SimulatorError):
|
|
119
|
+
"""The run database already holds a simulator run."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class ClockError(SimulatorError):
|
|
123
|
+
"""A call's virtual time is earlier than the run's last event."""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class ControlError(SimulatorError):
|
|
127
|
+
"""A control call that does not apply, such as revoking a pending approval."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _connect(conninfo: str) -> Connection:
|
|
131
|
+
conn = psycopg.connect(conninfo, autocommit=True)
|
|
132
|
+
try:
|
|
133
|
+
row = conn.execute("SELECT current_user").fetchone()
|
|
134
|
+
if row is None or row[0] != SIM_ROLE:
|
|
135
|
+
raise WrongRole(f"the simulator connects as {SIM_ROLE}, not {row}")
|
|
136
|
+
except BaseException:
|
|
137
|
+
conn.close()
|
|
138
|
+
raise
|
|
139
|
+
return conn
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _check_vt(vt: int) -> None:
|
|
143
|
+
if isinstance(vt, bool) or not isinstance(vt, int) or vt < 0:
|
|
144
|
+
raise ValueError(f"virtual time is a non-negative integer, not {vt!r}")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _check_name(name: str, what: str) -> None:
|
|
148
|
+
if not isinstance(name, str) or not name or "\x00" in name:
|
|
149
|
+
raise ValueError(f"{what} is named by non-empty text, not {name!r}")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def supplier_directory(scenario: Scenario) -> JsonObject:
|
|
153
|
+
"""The `suppliers` fact: every supplier with a quote or on the allowlist, in id order."""
|
|
154
|
+
quoted = {key.split("/")[1] for key in scenario.facts if fact_kind(key) is FactKind.QUOTE}
|
|
155
|
+
allowlist = set(scenario.authority.allowlist)
|
|
156
|
+
entries: list[JsonValue] = [
|
|
157
|
+
{"supplier_id": supplier_id, "allowlisted": supplier_id in allowlist}
|
|
158
|
+
for supplier_id in sorted(quoted | allowlist)
|
|
159
|
+
]
|
|
160
|
+
return {"suppliers": entries}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def setup_run(conninfo: str, scenario: Scenario, config: SimConfig, *, vt: int = 0) -> None:
|
|
164
|
+
"""Set up the simulator's run: its configuration and the scenario's facts at version 1.
|
|
165
|
+
|
|
166
|
+
Every initial fact, and the derived supplier directory, is valid from the setup
|
|
167
|
+
event. A run database holds one run, so a second setup is refused.
|
|
168
|
+
"""
|
|
169
|
+
_check_vt(vt)
|
|
170
|
+
conn = _connect(conninfo)
|
|
171
|
+
try:
|
|
172
|
+
with conn.transaction():
|
|
173
|
+
if conn.execute("SELECT 1 FROM sim.run").fetchone() is not None:
|
|
174
|
+
raise AlreadySetUp("this run database already holds a simulator run")
|
|
175
|
+
params = config.params
|
|
176
|
+
conn.execute(
|
|
177
|
+
"INSERT INTO sim.run (scenario_id, task_id, capabilities, max_hop_latency_ms,"
|
|
178
|
+
" commit_deadline_ms, status_lag_ms, credentials, authority)"
|
|
179
|
+
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
|
180
|
+
(
|
|
181
|
+
scenario.id,
|
|
182
|
+
scenario.task_id,
|
|
183
|
+
sorted(str(capability) for capability in config.capabilities),
|
|
184
|
+
params.max_hop_latency_ms,
|
|
185
|
+
params.commit_deadline_ms,
|
|
186
|
+
params.status_lag_ms,
|
|
187
|
+
sorted(config.credentials),
|
|
188
|
+
Jsonb(scenario.authority.model_dump(mode="json")),
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
ledger = Ledger(conn, vt)
|
|
192
|
+
seq = ledger.event("setup", SIM_ACTOR, scenario.id)
|
|
193
|
+
facts: dict[str, Mapping[str, object]] = dict(scenario.fact_values())
|
|
194
|
+
facts[SUPPLIERS_KEY] = supplier_directory(scenario)
|
|
195
|
+
for key in sorted(facts):
|
|
196
|
+
ledger.add_fact_version(key, 1, facts[key], seq, cause="initial")
|
|
197
|
+
finally:
|
|
198
|
+
conn.close()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class Simulator:
|
|
202
|
+
"""The simulator of one run. Close it, or use it as a context manager."""
|
|
203
|
+
|
|
204
|
+
def __init__(self, conninfo: str) -> None:
|
|
205
|
+
"""Open a run that `setup_run` has set up."""
|
|
206
|
+
self._conn = _connect(conninfo)
|
|
207
|
+
try:
|
|
208
|
+
row = self._conn.execute(
|
|
209
|
+
"SELECT scenario_id, task_id, capabilities, max_hop_latency_ms,"
|
|
210
|
+
" commit_deadline_ms, status_lag_ms, credentials, authority FROM sim.run"
|
|
211
|
+
).fetchone()
|
|
212
|
+
if row is None:
|
|
213
|
+
raise NotSetUp("the run database has no simulator run; call setup_run first")
|
|
214
|
+
self.scenario_id = str(row[0])
|
|
215
|
+
self.task_id = str(row[1])
|
|
216
|
+
self.config = SimConfig(
|
|
217
|
+
capabilities=frozenset(Capability(name) for name in row[2]),
|
|
218
|
+
credentials=frozenset(str(name) for name in row[6]),
|
|
219
|
+
params=ContractParams(
|
|
220
|
+
max_hop_latency_ms=int(row[3]),
|
|
221
|
+
commit_deadline_ms=int(row[4]),
|
|
222
|
+
status_lag_ms=int(row[5]),
|
|
223
|
+
),
|
|
224
|
+
)
|
|
225
|
+
self.authority = Authority.model_validate(row[7])
|
|
226
|
+
except BaseException:
|
|
227
|
+
self._conn.close()
|
|
228
|
+
raise
|
|
229
|
+
self.control = Control(self)
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def setup(
|
|
233
|
+
cls, conninfo: str, scenario: Scenario, config: SimConfig, *, vt: int = 0
|
|
234
|
+
) -> Simulator:
|
|
235
|
+
"""Set up the run (`setup_run`) and open it."""
|
|
236
|
+
setup_run(conninfo, scenario, config, vt=vt)
|
|
237
|
+
return cls(conninfo)
|
|
238
|
+
|
|
239
|
+
def close(self) -> None:
|
|
240
|
+
"""Close the connection. Closing twice does nothing."""
|
|
241
|
+
self._conn.close()
|
|
242
|
+
|
|
243
|
+
def __enter__(self) -> Simulator:
|
|
244
|
+
return self
|
|
245
|
+
|
|
246
|
+
def __exit__(
|
|
247
|
+
self,
|
|
248
|
+
kind: type[BaseException] | None,
|
|
249
|
+
error: BaseException | None,
|
|
250
|
+
traceback: TracebackType | None,
|
|
251
|
+
) -> None:
|
|
252
|
+
self.close()
|
|
253
|
+
|
|
254
|
+
# Transactions ----------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
@contextmanager
|
|
257
|
+
def _transaction(self, vt: int) -> Iterator[Ledger]:
|
|
258
|
+
"""One transaction at virtual time `vt`, holding the run's row lock.
|
|
259
|
+
|
|
260
|
+
Writes in flight past their commit deadline are aborted first (0005).
|
|
261
|
+
"""
|
|
262
|
+
_check_vt(vt)
|
|
263
|
+
with self._conn.transaction():
|
|
264
|
+
row = self._conn.execute("SELECT last_vt FROM sim.run FOR UPDATE").fetchone()
|
|
265
|
+
if row is None:
|
|
266
|
+
raise NotSetUp("the run database has no simulator run")
|
|
267
|
+
if vt < int(row[0]):
|
|
268
|
+
raise ClockError(f"virtual time {vt} is before the last event, at {row[0]}")
|
|
269
|
+
ledger = Ledger(self._conn, vt)
|
|
270
|
+
for overdue in ledger.overdue_writes():
|
|
271
|
+
seq = ledger.event("write_aborted", SIM_ACTOR, overdue.intent_id)
|
|
272
|
+
ledger.set_write_outcome(overdue.received_seq, "aborted", outcome_seq=seq)
|
|
273
|
+
ledger.aborted.append(overdue.received_seq)
|
|
274
|
+
yield ledger
|
|
275
|
+
|
|
276
|
+
def _allowed(self, caller: str) -> bool:
|
|
277
|
+
_check_name(caller, "a caller")
|
|
278
|
+
return caller in self.config.credentials
|
|
279
|
+
|
|
280
|
+
@staticmethod
|
|
281
|
+
def _forbidden(caller: str) -> Refusal:
|
|
282
|
+
return Refusal(
|
|
283
|
+
reason=RefusalReason.FORBIDDEN, detail=f"{caller} holds no credential for this run"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
# Reads -----------------------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
def get_quote(self, request: GetQuote, *, caller: str, vt: int) -> FactRead | Refusal:
|
|
289
|
+
"""Serve a supplier's quote for a sku."""
|
|
290
|
+
return self._read(quote_key(request.supplier_id, request.sku), caller=caller, vt=vt)
|
|
291
|
+
|
|
292
|
+
def list_suppliers(self, request: ListSuppliers, *, caller: str, vt: int) -> FactRead | Refusal:
|
|
293
|
+
"""Serve the supplier directory."""
|
|
294
|
+
return self._read(SUPPLIERS_KEY, caller=caller, vt=vt)
|
|
295
|
+
|
|
296
|
+
def get_budget(self, request: GetBudget, *, caller: str, vt: int) -> FactRead | Refusal:
|
|
297
|
+
"""Serve a cost center's budget."""
|
|
298
|
+
return self._read(budget_key(request.cost_center), caller=caller, vt=vt)
|
|
299
|
+
|
|
300
|
+
def get_inventory(self, request: GetInventory, *, caller: str, vt: int) -> FactRead | Refusal:
|
|
301
|
+
"""Serve a sku's stock in a warehouse."""
|
|
302
|
+
return self._read(inventory_key(request.warehouse_id, request.sku), caller=caller, vt=vt)
|
|
303
|
+
|
|
304
|
+
def _read(self, key: str, *, caller: str, vt: int) -> FactRead | Refusal:
|
|
305
|
+
"""Serve a fact's latest version, and log the read with its caller (0004)."""
|
|
306
|
+
if not self._allowed(caller):
|
|
307
|
+
return self._forbidden(caller)
|
|
308
|
+
with self._transaction(vt) as ledger:
|
|
309
|
+
latest = ledger.latest_fact(key)
|
|
310
|
+
if latest is None:
|
|
311
|
+
return Refusal(reason=RefusalReason.NOT_FOUND, detail=f"no fact {key}")
|
|
312
|
+
version, value = latest
|
|
313
|
+
seq = ledger.event("read", caller, key)
|
|
314
|
+
ledger.log_read(seq, key, version, caller)
|
|
315
|
+
return FactRead(key=key, version=version, data=value)
|
|
316
|
+
|
|
317
|
+
# Approvals -------------------------------------------------------------------------
|
|
318
|
+
|
|
319
|
+
def request_approval(
|
|
320
|
+
self, request: RequestApproval, *, caller: str, vt: int
|
|
321
|
+
) -> ApprovalAnswer | Refusal:
|
|
322
|
+
"""File an approval request, which policy decides at once or queues (0002, rule 6).
|
|
323
|
+
|
|
324
|
+
A request whose client request key was used before returns the original
|
|
325
|
+
approval as it stands now, and files nothing (rule 4).
|
|
326
|
+
"""
|
|
327
|
+
if not self._allowed(caller):
|
|
328
|
+
return self._forbidden(caller)
|
|
329
|
+
with self._transaction(vt) as ledger:
|
|
330
|
+
if request.client_request_key is not None:
|
|
331
|
+
original = ledger.approval_by_request_key(request.client_request_key)
|
|
332
|
+
if original is not None:
|
|
333
|
+
ledger.event("approval_repeated", caller, original.approval_id)
|
|
334
|
+
return self._approval_answer(original, vt, repeated=True)
|
|
335
|
+
approval_id = f"APR-{ledger.next_number('apr'):04d}"
|
|
336
|
+
seq = ledger.event("approval_requested", caller, approval_id)
|
|
337
|
+
scope = request.scope.model_dump()
|
|
338
|
+
ledger.insert_approval(
|
|
339
|
+
approval_id,
|
|
340
|
+
intent_id=request.intent_id,
|
|
341
|
+
operation=request.operation,
|
|
342
|
+
scope=scope,
|
|
343
|
+
client_request_key=request.client_request_key,
|
|
344
|
+
requester=caller,
|
|
345
|
+
requested_seq=seq,
|
|
346
|
+
)
|
|
347
|
+
ledger.add_approval_event(seq, approval_id, "requested", caller)
|
|
348
|
+
decision = self.authority.policy_decision(request.operation, scope)
|
|
349
|
+
if decision is not PolicyDecision.QUEUE:
|
|
350
|
+
self._decide(ledger, approval_id, Decision(decision.value), actor=POLICY_ACTOR)
|
|
351
|
+
return self._approval_answer(self._approval(ledger, approval_id), vt)
|
|
352
|
+
|
|
353
|
+
def get_approval_status(
|
|
354
|
+
self, request: GetApprovalStatus, *, caller: str, vt: int
|
|
355
|
+
) -> ApprovalAnswer | Refusal:
|
|
356
|
+
"""Report an approval's status now. The simulator never waits (see the module)."""
|
|
357
|
+
if not self._allowed(caller):
|
|
358
|
+
return self._forbidden(caller)
|
|
359
|
+
with self._transaction(vt) as ledger:
|
|
360
|
+
row = ledger.approval(request.approval_id)
|
|
361
|
+
if row is None:
|
|
362
|
+
return Refusal(
|
|
363
|
+
reason=RefusalReason.NOT_FOUND, detail=f"no approval {request.approval_id}"
|
|
364
|
+
)
|
|
365
|
+
ledger.event("approval_status", caller, row.approval_id)
|
|
366
|
+
return self._approval_answer(row, vt)
|
|
367
|
+
|
|
368
|
+
def _decide(self, ledger: Ledger, approval_id: str, decision: Decision, *, actor: str) -> None:
|
|
369
|
+
"""Decide a pending approval. An approval expires `approval_ttl_ms` later (rule 8)."""
|
|
370
|
+
if decision is Decision.APPROVE:
|
|
371
|
+
seq = ledger.event("approval_approved", actor, approval_id)
|
|
372
|
+
ledger.add_approval_event(seq, approval_id, "approved", actor)
|
|
373
|
+
expires_at = ledger.vt + self.authority.approval_ttl_ms
|
|
374
|
+
ledger.set_decision(
|
|
375
|
+
approval_id, "approved", seq=seq, actor=actor, expires_at=expires_at
|
|
376
|
+
)
|
|
377
|
+
else:
|
|
378
|
+
seq = ledger.event("approval_denied", actor, approval_id)
|
|
379
|
+
ledger.add_approval_event(seq, approval_id, "denied", actor)
|
|
380
|
+
ledger.set_decision(approval_id, "denied", seq=seq, actor=actor, expires_at=None)
|
|
381
|
+
|
|
382
|
+
@staticmethod
|
|
383
|
+
def _approval(ledger: Ledger, approval_id: str) -> ApprovalRow:
|
|
384
|
+
row = ledger.approval(approval_id)
|
|
385
|
+
if row is None:
|
|
386
|
+
raise ControlError(f"no approval {approval_id}")
|
|
387
|
+
return row
|
|
388
|
+
|
|
389
|
+
@staticmethod
|
|
390
|
+
def _approval_answer(row: ApprovalRow, vt: int, *, repeated: bool = False) -> ApprovalAnswer:
|
|
391
|
+
return ApprovalAnswer(
|
|
392
|
+
approval_id=row.approval_id,
|
|
393
|
+
intent_id=row.intent_id,
|
|
394
|
+
operation=row.operation,
|
|
395
|
+
scope=SCOPE_MODELS[row.operation].model_validate(row.scope),
|
|
396
|
+
status=row.status_at(vt),
|
|
397
|
+
requested_vt=row.requested_vt,
|
|
398
|
+
decided_vt=row.decided_vt,
|
|
399
|
+
decided_by=row.decided_by,
|
|
400
|
+
expires_at=row.expires_at,
|
|
401
|
+
revoked_vt=row.revoked_vt,
|
|
402
|
+
repeated=repeated,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
# Writes ----------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
def submit_purchase_order(
|
|
408
|
+
self, request: SubmitPurchaseOrder, *, caller: str, vt: int
|
|
409
|
+
) -> WriteAnswer:
|
|
410
|
+
"""Receive a purchase order and commit it at once, in one transaction."""
|
|
411
|
+
return self._submit(request, caller=caller, vt=vt)
|
|
412
|
+
|
|
413
|
+
def reserve_inventory(self, request: ReserveInventory, *, caller: str, vt: int) -> WriteAnswer:
|
|
414
|
+
"""Receive a reservation and commit it at once, in one transaction."""
|
|
415
|
+
return self._submit(request, caller=caller, vt=vt)
|
|
416
|
+
|
|
417
|
+
def receive_write(
|
|
418
|
+
self, request: Write, *, caller: str, vt: int, waive_deadline: bool = False
|
|
419
|
+
) -> WriteAnswer | WriteReceived:
|
|
420
|
+
"""The harness's split path, first half: the write reaches the destination now.
|
|
421
|
+
|
|
422
|
+
A key lookup may answer at once (a replay, or `in_progress`). Otherwise the write
|
|
423
|
+
is in flight until `commit_received`, which must come by its deadline (arrival
|
|
424
|
+
plus D) or the write aborts. `waive_deadline` is fault F5 beyond the deadline, a
|
|
425
|
+
contract violation: the write can then commit later than D (0006).
|
|
426
|
+
"""
|
|
427
|
+
if not self._allowed(caller):
|
|
428
|
+
return self._forbidden_write(caller)
|
|
429
|
+
with self._transaction(vt) as ledger:
|
|
430
|
+
received = self._receive(ledger, request, caller, waive_deadline=waive_deadline)
|
|
431
|
+
if not isinstance(received, WriteRow):
|
|
432
|
+
return received
|
|
433
|
+
return WriteReceived(
|
|
434
|
+
received_seq=received.received_seq, deadline_vt=received.deadline_vt
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
def commit_received(self, received_seq: int, *, vt: int) -> WriteAnswer | WriteAborted:
|
|
438
|
+
"""The harness's split path, second half: commit a write that is in flight.
|
|
439
|
+
|
|
440
|
+
Returns `WriteAborted` if the write missed its deadline.
|
|
441
|
+
"""
|
|
442
|
+
with self._transaction(vt) as ledger:
|
|
443
|
+
write = ledger.write(received_seq)
|
|
444
|
+
if write is None:
|
|
445
|
+
raise ControlError(f"no write received at seq {received_seq}")
|
|
446
|
+
if write.state == "aborted":
|
|
447
|
+
return WriteAborted(received_seq=received_seq, deadline_vt=write.deadline_vt)
|
|
448
|
+
if write.state != "received":
|
|
449
|
+
raise ControlError(f"write {received_seq} already ended as {write.state}")
|
|
450
|
+
return self._commit(ledger, write)
|
|
451
|
+
|
|
452
|
+
def _submit(self, request: Write, *, caller: str, vt: int) -> WriteAnswer:
|
|
453
|
+
if not self._allowed(caller):
|
|
454
|
+
return self._forbidden_write(caller)
|
|
455
|
+
with self._transaction(vt) as ledger:
|
|
456
|
+
received = self._receive(ledger, request, caller, waive_deadline=False)
|
|
457
|
+
if not isinstance(received, WriteRow):
|
|
458
|
+
return received
|
|
459
|
+
return self._commit(ledger, received)
|
|
460
|
+
|
|
461
|
+
@staticmethod
|
|
462
|
+
def _forbidden_write(caller: str) -> WriteRejected:
|
|
463
|
+
return WriteRejected(
|
|
464
|
+
reason=WriteRejectReason.FORBIDDEN,
|
|
465
|
+
detail=f"{caller} holds no credential for this run",
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
def _receive(
|
|
469
|
+
self, ledger: Ledger, request: Write, caller: str, *, waive_deadline: bool
|
|
470
|
+
) -> WriteAnswer | WriteRow:
|
|
471
|
+
"""Record a write's arrival, then look up its key (0005).
|
|
472
|
+
|
|
473
|
+
With the idempotency_key capability, a key that already committed gets the stored
|
|
474
|
+
result, marked as a replay, and a key in flight gets `in_progress`. Otherwise the
|
|
475
|
+
write is in flight, and its row is returned.
|
|
476
|
+
"""
|
|
477
|
+
key = request.idempotency_key
|
|
478
|
+
honoured = self.config.has(Capability.IDEMPOTENCY_KEY) and key is not None
|
|
479
|
+
received_seq = ledger.event("write_received", caller, request.intent_id)
|
|
480
|
+
new = NewWrite(
|
|
481
|
+
received_seq=received_seq,
|
|
482
|
+
caller=caller,
|
|
483
|
+
operation=request.operation,
|
|
484
|
+
intent_id=request.intent_id,
|
|
485
|
+
approval_id=request.approval_id,
|
|
486
|
+
args=request.business_args(),
|
|
487
|
+
basis=dict(request.basis),
|
|
488
|
+
idempotency_key=key,
|
|
489
|
+
key_honoured=honoured,
|
|
490
|
+
client_ref=request.client_ref,
|
|
491
|
+
deadline_vt=ledger.vt + self.config.params.commit_deadline_ms,
|
|
492
|
+
deadline_waived=waive_deadline,
|
|
493
|
+
)
|
|
494
|
+
if honoured and key is not None:
|
|
495
|
+
stored = ledger.effect_by_key(key)
|
|
496
|
+
if stored is not None:
|
|
497
|
+
seq = ledger.event("write_replayed", caller, request.intent_id)
|
|
498
|
+
ledger.insert_write(
|
|
499
|
+
new, state="replayed", outcome_seq=seq, effect_id=stored.effect_id
|
|
500
|
+
)
|
|
501
|
+
return self._committed(stored, replay=True)
|
|
502
|
+
if ledger.key_in_flight(key):
|
|
503
|
+
seq = ledger.event("write_in_progress", caller, request.intent_id)
|
|
504
|
+
ledger.insert_write(new, state="in_progress", outcome_seq=seq)
|
|
505
|
+
return WriteInProgress(idempotency_key=key)
|
|
506
|
+
ledger.insert_write(new)
|
|
507
|
+
write = ledger.write(received_seq)
|
|
508
|
+
if write is None:
|
|
509
|
+
raise SimulatorError(f"write {received_seq} was not recorded")
|
|
510
|
+
return write
|
|
511
|
+
|
|
512
|
+
def _commit(self, ledger: Ledger, write: WriteRow) -> WriteAnswer:
|
|
513
|
+
"""Decide a write in flight, inside the commit transaction (0005).
|
|
514
|
+
|
|
515
|
+
The key lookup already happened on arrival (`_receive`). While this write is in
|
|
516
|
+
flight, any other write with its key got `in_progress`, so no effect can have
|
|
517
|
+
stored the key since. The unique index on `sim.effect.idempotency_key` still
|
|
518
|
+
enforces this inside the commit transaction: a late duplicate fails the
|
|
519
|
+
transaction instead of creating a second effect. At C3 the preconditions come
|
|
520
|
+
next. Then the write commits: one effect, and its consequence as a new version of
|
|
521
|
+
the budget or the stock.
|
|
522
|
+
"""
|
|
523
|
+
if self.config.has(Capability.CONDITIONAL_WRITE):
|
|
524
|
+
failed = self._preconditions(ledger, write)
|
|
525
|
+
if failed:
|
|
526
|
+
rejection = WriteRejected(
|
|
527
|
+
reason=WriteRejectReason.PRECONDITION_FAILED, failed_checks=failed
|
|
528
|
+
)
|
|
529
|
+
return self._reject(ledger, write, rejection)
|
|
530
|
+
target = consequence_key(write.operation, write.args)
|
|
531
|
+
current = ledger.latest_fact(target)
|
|
532
|
+
if current is None:
|
|
533
|
+
rejection = WriteRejected(
|
|
534
|
+
reason=WriteRejectReason.UNKNOWN_FACT, detail=f"no fact {target}"
|
|
535
|
+
)
|
|
536
|
+
return self._reject(ledger, write, rejection)
|
|
537
|
+
seq = ledger.event("write_committed", write.caller, write.intent_id)
|
|
538
|
+
if write.operation is Operation.SUBMIT_PURCHASE_ORDER:
|
|
539
|
+
effect_id = f"PO-{ledger.next_number('po'):04d}"
|
|
540
|
+
else:
|
|
541
|
+
effect_id = f"RS-{ledger.next_number('rs'):04d}"
|
|
542
|
+
ledger.insert_effect(effect_id, write, commit_seq=seq)
|
|
543
|
+
version, value = current
|
|
544
|
+
ledger.add_fact_version(
|
|
545
|
+
target,
|
|
546
|
+
version + 1,
|
|
547
|
+
consequence(write.operation, write.args, value),
|
|
548
|
+
seq,
|
|
549
|
+
cause="effect",
|
|
550
|
+
effect_id=effect_id,
|
|
551
|
+
)
|
|
552
|
+
approval = ledger.approval(write.approval_id)
|
|
553
|
+
if approval is not None and approval.effect_id is None:
|
|
554
|
+
ledger.set_backed_effect(write.approval_id, effect_id)
|
|
555
|
+
ledger.set_write_outcome(
|
|
556
|
+
write.received_seq, "committed", outcome_seq=seq, effect_id=effect_id
|
|
557
|
+
)
|
|
558
|
+
return WriteCommitted(
|
|
559
|
+
effect_id=effect_id,
|
|
560
|
+
replay=False,
|
|
561
|
+
intent_id=write.intent_id,
|
|
562
|
+
operation=write.operation,
|
|
563
|
+
args=write.args,
|
|
564
|
+
committed_vt=ledger.vt,
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
def _preconditions(self, ledger: Ledger, write: WriteRow) -> list[FailedCheck]:
|
|
568
|
+
"""The conditional write's checks at commit: authority, then each input (0005).
|
|
569
|
+
|
|
570
|
+
The approval must be approved, unrevoked and unexpired now, in scope for the write,
|
|
571
|
+
and back no effect yet (0002, rule 11). Each dependency must be declared in the
|
|
572
|
+
basis, served before the write arrived, and satisfy its rule now (0004).
|
|
573
|
+
"""
|
|
574
|
+
failed: list[FailedCheck] = []
|
|
575
|
+
approval = ledger.approval(write.approval_id)
|
|
576
|
+
if approval is None:
|
|
577
|
+
failed.append(FailedCheck(check=CheckName.APPROVAL_UNKNOWN))
|
|
578
|
+
else:
|
|
579
|
+
status = approval.status_at(ledger.vt)
|
|
580
|
+
if status is not ApprovalStatus.APPROVED:
|
|
581
|
+
failed.append(FailedCheck(check=_STATUS_CHECKS[status]))
|
|
582
|
+
mismatched = scope_mismatches(
|
|
583
|
+
approval_intent_id=approval.intent_id,
|
|
584
|
+
approval_operation=approval.operation,
|
|
585
|
+
scope=approval.scope,
|
|
586
|
+
intent_id=write.intent_id,
|
|
587
|
+
operation=write.operation,
|
|
588
|
+
args=write.args,
|
|
589
|
+
)
|
|
590
|
+
if mismatched:
|
|
591
|
+
failed.append(
|
|
592
|
+
FailedCheck(
|
|
593
|
+
check=CheckName.APPROVAL_OUT_OF_SCOPE, mismatched_fields=list(mismatched)
|
|
594
|
+
)
|
|
595
|
+
)
|
|
596
|
+
if approval.effect_id is not None:
|
|
597
|
+
failed.append(
|
|
598
|
+
FailedCheck(check=CheckName.APPROVAL_USED, effect_id=approval.effect_id)
|
|
599
|
+
)
|
|
600
|
+
history = History(ledger, write.received_seq)
|
|
601
|
+
for check in check_basis(write.operation, write.args, write.basis, history):
|
|
602
|
+
if check.failure is not None:
|
|
603
|
+
failed.append(
|
|
604
|
+
FailedCheck(
|
|
605
|
+
check=CheckName(check.failure.value),
|
|
606
|
+
key=check.dependency.key,
|
|
607
|
+
cited_version=check.cited_version,
|
|
608
|
+
current_version=check.current_version,
|
|
609
|
+
changed_fields=list(check.changed_fields),
|
|
610
|
+
)
|
|
611
|
+
)
|
|
612
|
+
return failed
|
|
613
|
+
|
|
614
|
+
@staticmethod
|
|
615
|
+
def _reject(ledger: Ledger, write: WriteRow, rejection: WriteRejected) -> WriteRejected:
|
|
616
|
+
seq = ledger.event("write_rejected", write.caller, write.intent_id)
|
|
617
|
+
ledger.set_write_outcome(
|
|
618
|
+
write.received_seq,
|
|
619
|
+
"rejected",
|
|
620
|
+
outcome_seq=seq,
|
|
621
|
+
rejection=rejection.model_dump(mode="json"),
|
|
622
|
+
)
|
|
623
|
+
return rejection
|
|
624
|
+
|
|
625
|
+
@staticmethod
|
|
626
|
+
def _committed(effect: EffectRow, *, replay: bool) -> WriteCommitted:
|
|
627
|
+
return WriteCommitted(
|
|
628
|
+
effect_id=effect.effect_id,
|
|
629
|
+
replay=replay,
|
|
630
|
+
intent_id=effect.intent_id,
|
|
631
|
+
operation=effect.operation,
|
|
632
|
+
args=effect.args,
|
|
633
|
+
committed_vt=effect.committed_vt,
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
# Status (C1) -----------------------------------------------------------------------
|
|
637
|
+
|
|
638
|
+
def get_order_status(
|
|
639
|
+
self,
|
|
640
|
+
request: GetOrderStatus,
|
|
641
|
+
*,
|
|
642
|
+
caller: str,
|
|
643
|
+
vt: int,
|
|
644
|
+
as_of_vt: int | None = None,
|
|
645
|
+
reflect_vt: int | None = None,
|
|
646
|
+
contract_violation: bool = False,
|
|
647
|
+
) -> StatusAnswer | Refusal:
|
|
648
|
+
"""Which purchase orders exist for an intent (`_status` explains the options)."""
|
|
649
|
+
return self._status(
|
|
650
|
+
Operation.SUBMIT_PURCHASE_ORDER,
|
|
651
|
+
request.intent_id,
|
|
652
|
+
caller=caller,
|
|
653
|
+
vt=vt,
|
|
654
|
+
as_of_vt=as_of_vt,
|
|
655
|
+
reflect_vt=reflect_vt,
|
|
656
|
+
contract_violation=contract_violation,
|
|
657
|
+
)
|
|
658
|
+
|
|
659
|
+
def get_reservation_status(
|
|
660
|
+
self,
|
|
661
|
+
request: GetReservationStatus,
|
|
662
|
+
*,
|
|
663
|
+
caller: str,
|
|
664
|
+
vt: int,
|
|
665
|
+
as_of_vt: int | None = None,
|
|
666
|
+
reflect_vt: int | None = None,
|
|
667
|
+
contract_violation: bool = False,
|
|
668
|
+
) -> StatusAnswer | Refusal:
|
|
669
|
+
"""Which reservations exist for an intent (`_status` explains the options)."""
|
|
670
|
+
return self._status(
|
|
671
|
+
Operation.RESERVE_INVENTORY,
|
|
672
|
+
request.intent_id,
|
|
673
|
+
caller=caller,
|
|
674
|
+
vt=vt,
|
|
675
|
+
as_of_vt=as_of_vt,
|
|
676
|
+
reflect_vt=reflect_vt,
|
|
677
|
+
contract_violation=contract_violation,
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
def _status(
|
|
681
|
+
self,
|
|
682
|
+
operation: Operation,
|
|
683
|
+
intent_id: str,
|
|
684
|
+
*,
|
|
685
|
+
caller: str,
|
|
686
|
+
vt: int,
|
|
687
|
+
as_of_vt: int | None,
|
|
688
|
+
reflect_vt: int | None,
|
|
689
|
+
contract_violation: bool,
|
|
690
|
+
) -> StatusAnswer | Refusal:
|
|
691
|
+
"""Answer a status lookup, accurate to `as_of_vt` (0005).
|
|
692
|
+
|
|
693
|
+
By default the answer is fresh: `as_of_vt` is `vt`. The harness may make it stale,
|
|
694
|
+
down to `vt - status_lag_ms`, as the destination's lag allows (F10, stale within
|
|
695
|
+
L). An answer that lists the effects as of `reflect_vt` while claiming another
|
|
696
|
+
`as_of_vt`, or that is staler than L, breaks the destination's promise; only a
|
|
697
|
+
fault may ask for one, with `contract_violation` (F10, stale beyond L).
|
|
698
|
+
"""
|
|
699
|
+
if not self._allowed(caller):
|
|
700
|
+
return self._forbidden(caller)
|
|
701
|
+
if not self.config.has(Capability.STATUS):
|
|
702
|
+
return Refusal(
|
|
703
|
+
reason=RefusalReason.UNSUPPORTED, detail="this destination has no status lookup"
|
|
704
|
+
)
|
|
705
|
+
_check_vt(vt)
|
|
706
|
+
claimed = vt if as_of_vt is None else as_of_vt
|
|
707
|
+
reflected = claimed if reflect_vt is None else reflect_vt
|
|
708
|
+
_check_vt(claimed)
|
|
709
|
+
_check_vt(reflected)
|
|
710
|
+
if claimed > vt or reflected > vt:
|
|
711
|
+
raise ValueError("a status answer cannot reflect the future")
|
|
712
|
+
within_lag = claimed >= vt - self.config.params.status_lag_ms
|
|
713
|
+
if (not within_lag or reflected != claimed) and not contract_violation:
|
|
714
|
+
raise ValueError(
|
|
715
|
+
"this answer breaks the status promise; only a fault may ask for it"
|
|
716
|
+
" (contract_violation=True)"
|
|
717
|
+
)
|
|
718
|
+
with self._transaction(vt) as ledger:
|
|
719
|
+
effects = ledger.effects_for(intent_id, operation, reflected)
|
|
720
|
+
ledger.event("status", caller, intent_id)
|
|
721
|
+
return StatusAnswer(
|
|
722
|
+
intent_id=intent_id,
|
|
723
|
+
operation=operation,
|
|
724
|
+
effects=[
|
|
725
|
+
StatusEffect(effect_id=effect.effect_id, args=effect.args) for effect in effects
|
|
726
|
+
],
|
|
727
|
+
as_of_vt=claimed,
|
|
728
|
+
)
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
class Control:
|
|
732
|
+
"""The harness's control interface: scripted humans and fault plans (0002, 0006).
|
|
733
|
+
|
|
734
|
+
It is in-process only. Agents never get it: they reach the simulator through the
|
|
735
|
+
harness's transports (B modes) or not at all (G modes).
|
|
736
|
+
"""
|
|
737
|
+
|
|
738
|
+
def __init__(self, simulator: Simulator) -> None:
|
|
739
|
+
self._sim = simulator
|
|
740
|
+
|
|
741
|
+
def decide(
|
|
742
|
+
self, approval_id: str, decision: Decision, *, actor: str, vt: int
|
|
743
|
+
) -> ApprovalAnswer:
|
|
744
|
+
"""The scripted approver decides a queued request (0002, rule 7)."""
|
|
745
|
+
_check_name(actor, "an actor")
|
|
746
|
+
sim = self._sim
|
|
747
|
+
with sim._transaction(vt) as ledger:
|
|
748
|
+
row = sim._approval(ledger, approval_id)
|
|
749
|
+
if row.status != "pending":
|
|
750
|
+
raise ControlError(f"approval {approval_id} is {row.status}, not pending")
|
|
751
|
+
sim._decide(ledger, approval_id, decision, actor=actor)
|
|
752
|
+
return sim._approval_answer(sim._approval(ledger, approval_id), vt)
|
|
753
|
+
|
|
754
|
+
def revoke(self, approval_id: str, *, actor: str, vt: int) -> ApprovalAnswer:
|
|
755
|
+
"""Revoke an approved approval, for good (0002, rule 8; fault F6)."""
|
|
756
|
+
_check_name(actor, "an actor")
|
|
757
|
+
sim = self._sim
|
|
758
|
+
with sim._transaction(vt) as ledger:
|
|
759
|
+
row = sim._approval(ledger, approval_id)
|
|
760
|
+
if row.status != "approved":
|
|
761
|
+
raise ControlError(f"approval {approval_id} is {row.status}; only approved ones")
|
|
762
|
+
seq = ledger.event("approval_revoked", actor, approval_id)
|
|
763
|
+
ledger.add_approval_event(seq, approval_id, "revoked", actor)
|
|
764
|
+
ledger.set_revocation(approval_id, seq=seq, actor=actor)
|
|
765
|
+
return sim._approval_answer(sim._approval(ledger, approval_id), vt)
|
|
766
|
+
|
|
767
|
+
def change_fact(
|
|
768
|
+
self, key: str, changes: Mapping[str, str | int], *, actor: str, vt: int
|
|
769
|
+
) -> FactRead:
|
|
770
|
+
"""Append a version of a quote, budget or stock with some fields changed (fault F7).
|
|
771
|
+
|
|
772
|
+
The new version is caused by `actor`. It is not a read, so it is not logged as one.
|
|
773
|
+
"""
|
|
774
|
+
_check_name(actor, "an actor")
|
|
775
|
+
try:
|
|
776
|
+
kind = fact_kind(key)
|
|
777
|
+
except ValueError as error:
|
|
778
|
+
raise ControlError(str(error)) from error
|
|
779
|
+
if kind is FactKind.SUPPLIERS:
|
|
780
|
+
raise ControlError("the supplier directory never changes")
|
|
781
|
+
if not changes:
|
|
782
|
+
raise ControlError("a change names at least one field")
|
|
783
|
+
with self._sim._transaction(vt) as ledger:
|
|
784
|
+
latest = ledger.latest_fact(key)
|
|
785
|
+
if latest is None:
|
|
786
|
+
raise ControlError(f"no fact {key}")
|
|
787
|
+
version, current = latest
|
|
788
|
+
unknown = sorted(set(changes) - set(current))
|
|
789
|
+
if unknown:
|
|
790
|
+
raise ControlError(f"fact {key} has no fields {unknown}")
|
|
791
|
+
value: JsonObject = dict(current)
|
|
792
|
+
value.update(changes)
|
|
793
|
+
try:
|
|
794
|
+
FACT_MODELS[kind].model_validate(value)
|
|
795
|
+
except ValidationError as error:
|
|
796
|
+
raise ControlError(f"the change breaks fact {key}: {error}") from error
|
|
797
|
+
if value == current:
|
|
798
|
+
raise ControlError(f"the change leaves fact {key} as it is")
|
|
799
|
+
seq = ledger.event("fact_changed", actor, key)
|
|
800
|
+
ledger.add_fact_version(key, version + 1, value, seq, cause="control", actor=actor)
|
|
801
|
+
return FactRead(key=key, version=version + 1, data=json_object(value))
|
|
802
|
+
|
|
803
|
+
def current_fact(self, key: str) -> FactRead | None:
|
|
804
|
+
"""The latest version of a fact, read without serving it: no read is logged.
|
|
805
|
+
|
|
806
|
+
Fault plans use it to compute a change, such as F7's new price (0006).
|
|
807
|
+
"""
|
|
808
|
+
sim = self._sim
|
|
809
|
+
with sim._conn.transaction():
|
|
810
|
+
row = sim._conn.execute("SELECT last_vt FROM sim.run").fetchone()
|
|
811
|
+
vt = 0 if row is None else int(row[0])
|
|
812
|
+
latest = Ledger(sim._conn, vt).latest_fact(key)
|
|
813
|
+
if latest is None:
|
|
814
|
+
return None
|
|
815
|
+
version, value = latest
|
|
816
|
+
return FactRead(key=key, version=version, data=json_object(value))
|
|
817
|
+
|
|
818
|
+
def pending_approvals(self) -> list[ApprovalAnswer]:
|
|
819
|
+
"""Requests waiting for the scripted approver, in the order they were filed."""
|
|
820
|
+
sim = self._sim
|
|
821
|
+
with sim._conn.transaction():
|
|
822
|
+
row = sim._conn.execute("SELECT last_vt FROM sim.run").fetchone()
|
|
823
|
+
vt = 0 if row is None else int(row[0])
|
|
824
|
+
ledger = Ledger(sim._conn, vt)
|
|
825
|
+
return [sim._approval_answer(item, vt) for item in ledger.pending_approvals()]
|
|
826
|
+
|
|
827
|
+
def abort_overdue(self, *, vt: int) -> list[int]:
|
|
828
|
+
"""Abort every write in flight past its deadline, as every call does first.
|
|
829
|
+
|
|
830
|
+
The harness calls this when the drain window ends (0009), so the ledger shows
|
|
831
|
+
every write that never committed as aborted. Returns their received seqs.
|
|
832
|
+
"""
|
|
833
|
+
with self._sim._transaction(vt) as ledger:
|
|
834
|
+
return list(ledger.aborted)
|