amiril 0.0.0.dev0__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 (64) hide show
  1. amiril/__init__.py +51 -0
  2. amiril/_adapters.py +399 -0
  3. amiril/_engine/__init__.py +1 -0
  4. amiril/_engine/engine.py +113 -0
  5. amiril/_engine/expr.py +653 -0
  6. amiril/_engine/numbers.py +111 -0
  7. amiril/_engine/regex.py +262 -0
  8. amiril/_engine/rules.py +192 -0
  9. amiril/_engine/sentence.py +251 -0
  10. amiril/_engine/timeparse.py +72 -0
  11. amiril/_engine/validate.py +863 -0
  12. amiril/_engine/values.py +273 -0
  13. amiril/_kernel/__init__.py +1 -0
  14. amiril/_kernel/bundle.py +245 -0
  15. amiril/_kernel/coerce.py +103 -0
  16. amiril/_kernel/events.py +87 -0
  17. amiril/_kernel/guard.py +1196 -0
  18. amiril/_kernel/ids.py +66 -0
  19. amiril/_kernel/messages.py +30 -0
  20. amiril/_kernel/normalise.py +165 -0
  21. amiril/_kernel/records.py +131 -0
  22. amiril/_kernel/store.py +661 -0
  23. amiril/_runtime.py +617 -0
  24. amiril/adk.py +577 -0
  25. amiril/control/__init__.py +25 -0
  26. amiril/control/_delivery.py +567 -0
  27. amiril/control/_disk.py +418 -0
  28. amiril/control/_holds.py +252 -0
  29. amiril/control/_jsonschema.py +265 -0
  30. amiril/control/_pathc.py +85 -0
  31. amiril/control/_records.py +293 -0
  32. amiril/control/_redact.py +79 -0
  33. amiril/control/_transport.py +184 -0
  34. amiril/control/_wire.py +73 -0
  35. amiril/control/client.py +1313 -0
  36. amiril/control/config.py +204 -0
  37. amiril/control/schemas/bundle.response.schema.json +22 -0
  38. amiril/control/schemas/common.schema.json +593 -0
  39. amiril/control/schemas/decisions.request.schema.json +558 -0
  40. amiril/control/schemas/decisions.response.schema.json +23 -0
  41. amiril/control/schemas/error.response.schema.json +54 -0
  42. amiril/control/schemas/heartbeat.request.schema.json +305 -0
  43. amiril/control/schemas/heartbeat.response.schema.json +34 -0
  44. amiril/control/schemas/hold-create.request.schema.json +138 -0
  45. amiril/control/schemas/hold.response.schema.json +226 -0
  46. amiril/control/schemas/installation-register.request.schema.json +492 -0
  47. amiril/control/schemas/installation-register.response.schema.json +85 -0
  48. amiril/core.py +89 -0
  49. amiril/docs/README.md +14 -0
  50. amiril/docs/durability/langgraph.md +292 -0
  51. amiril/docs/frameworks/adk.md +141 -0
  52. amiril/docs/frameworks/langgraph.md +154 -0
  53. amiril/docs/frameworks/no-framework.md +238 -0
  54. amiril/docs/frameworks/write-an-adapter.md +203 -0
  55. amiril/durable.py +342 -0
  56. amiril/langgraph.py +746 -0
  57. amiril/plain.py +454 -0
  58. amiril/py.typed +0 -0
  59. amiril/seams.py +357 -0
  60. amiril/testing.py +21 -0
  61. amiril-0.0.0.dev0.dist-info/METADATA +114 -0
  62. amiril-0.0.0.dev0.dist-info/RECORD +64 -0
  63. amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
  64. amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,661 @@
1
+ """The history store (spec/kernel.md, section 4): records by root run and by
2
+ (agent, session), arrival order, batch-atomic snapshots, bounded by eviction,
3
+ with the history report the heartbeat carries.
4
+
5
+ Snapshots are views: `snapshot()` returns a list of references to the stored
6
+ records, never copies, and the first snapshot of a batch is cached per
7
+ `(root_run_id, batch_id)` so every sibling sees the same records in the same
8
+ state (4.2). Only the newest batch's snapshot per root run is kept: a newer
9
+ batch replaces it, a late sibling of an older batch recomputes, and a post
10
+ evaluation always builds a fresh one. A stored record is never mutated;
11
+ `update` and `complete` replace the object under its (root run, call id,
12
+ attempt) key. Call identity is scoped to the root run (kernel.md 5): the same
13
+ call id in two root runs is two calls.
14
+
15
+ Bookkeeping per batch and call id (batch marks and snapshots, attempt
16
+ counters) lives only while a record it describes does, so it is bounded by
17
+ `max_records` (4.3). A run's `seq` counter is the exception the spec makes:
18
+ it lives, with its run unit, until the run ends or is evicted as idle, so
19
+ `seq` never restarts inside a live run.
20
+
21
+ With a durable store (kernel.md 4.1a, `amiril.seams.DurableStore`) every
22
+ write here is mirrored to it, synchronously, after the in-memory change:
23
+ `persist` (the guard's write of a record with its outcome), `update` and
24
+ `complete` put the record; every drop deletes it; closing a run deletes its
25
+ `seq` counter. `restore` is the reverse: records loaded from the durable
26
+ store take their place in memory in their stored order, before anything new.
27
+ A durable store that raises never breaks the in-memory path: the error goes
28
+ to `on_durable_error` and the memory store is the truth for this process.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import dataclasses
34
+ import threading
35
+ import time
36
+ from collections.abc import Callable
37
+ from typing import Any
38
+
39
+ from .normalise import canonical_json
40
+ from .records import CallRecord
41
+
42
+ Key = tuple[str, str, int] # (root run id, call id, attempt)
43
+ CallKey = tuple[str, str] # (root run id, call id)
44
+
45
+ DEFAULT_MAX_RECORDS = 20000
46
+ DEFAULT_RUN_IDLE_MS = 3600000
47
+ DEFAULT_SESSION_IDLE_MS = 86400000
48
+ DEFAULT_MAX_RESULT_BYTES = 65536
49
+
50
+
51
+ class _Unit:
52
+ """A root run or an (agent, session): its records in arrival order and its
53
+ last activity. A run unit is `open` until `end_run` or idle eviction closes
54
+ it; it lives on closed while records with a session remain for session scope."""
55
+
56
+ __slots__ = ("records", "last_activity", "open", "first_arrival")
57
+
58
+ def __init__(self, first_arrival: int = 0) -> None:
59
+ self.records: dict[Key, CallRecord] = {}
60
+ self.last_activity: float = 0.0
61
+ self.open = True
62
+ self.first_arrival = first_arrival # records of this root run that arrived earlier belong to an evicted run
63
+
64
+
65
+ class HistoryStore:
66
+ def __init__(self, *, max_records: int = DEFAULT_MAX_RECORDS, run_idle_ms: int = DEFAULT_RUN_IDLE_MS,
67
+ session_idle_ms: int = DEFAULT_SESSION_IDLE_MS, clock: Callable[[], float] = time.time,
68
+ durable: Any = None,
69
+ on_durable_error: Callable[[BaseException, CallRecord | None], None] | None = None,
70
+ max_result_bytes: int = DEFAULT_MAX_RESULT_BYTES) -> None:
71
+ self.max_records = max_records
72
+ self.max_result_bytes = max_result_bytes
73
+ self.run_idle_ms = run_idle_ms
74
+ self.session_idle_ms = session_idle_ms
75
+ self.clock = clock
76
+ self.durable = durable
77
+ self.on_durable_error = on_durable_error
78
+ self._dropped: list[Key] = [] # keys dropped under the lock, deleted from the durable store on flush
79
+ self._closed: list[str] = [] # runs closed under the lock, likewise
80
+ self._ended: list[str] = [] # runs ended under the lock: deleted from the file directly (4.1a)
81
+ self._lock = threading.RLock()
82
+ self._records: dict[Key, CallRecord] = {}
83
+ self._attempts: dict[CallKey, int] = {} # highest attempt stored while one remains (4.1, 5)
84
+ self._count_by_call: dict[CallKey, int] = {}
85
+ self._roots_by_call: dict[str, dict[str, None]] = {} # call id -> root runs holding it, oldest first
86
+ self._runs: dict[str, _Unit] = {} # root run id -> unit; exists while the run has records
87
+ self._sessions: dict[tuple[str, str], _Unit] = {}
88
+ self._seq: dict[str, int] = {} # root run id -> last seq; lives with the open run (4.3)
89
+ self._batch_first: dict[tuple[str, str], int] = {}
90
+ self._batch_count: dict[tuple[str, str], int] = {}
91
+ self._batch_snapshot: dict[str, tuple[str, list[CallRecord]]] = {} # root run id -> (newest batch, view)
92
+ self._latest_batch: dict[str, str] = {} # root run id -> newest batch id seen
93
+ self._next_arrival = 0
94
+ self.evicted_runs = 0
95
+ self.evicted_sessions = 0
96
+ self.evicted_records_by_age = 0
97
+ self.evicted_records_by_size = 0
98
+ self.over_limit_events = 0
99
+
100
+ # ------------------------------------------------------------ writes
101
+
102
+ def capped(self, rec: CallRecord) -> CallRecord:
103
+ """4.3 `history.max_result_bytes`: the record as history keeps it. A
104
+ result whose canonical JSON is longer than the limit in UTF-8 bytes is
105
+ replaced by `{"$truncated": true, "bytes": <size>}`, so a later call
106
+ reading a field of it reads Absent; the record itself is unchanged."""
107
+ if rec.result is None:
108
+ return rec
109
+ size = len(canonical_json(rec.result).encode("utf-8", "surrogatepass"))
110
+ if size <= self.max_result_bytes:
111
+ return rec
112
+ return dataclasses.replace(rec, result={"$truncated": True, "bytes": size})
113
+
114
+ def next_attempt(self, call_id: str, root_run_id: str) -> int:
115
+ """The attempt a new record of this call id in this root run gets: one
116
+ above any attempt stored while one of them remains, so an evicted latest
117
+ attempt never collides with a surviving older one."""
118
+ with self._lock:
119
+ return self._attempts.get((root_run_id, call_id), 0) + 1
120
+
121
+ def append(self, rec: CallRecord) -> list[CallRecord]:
122
+ """Assign `seq` and the arrival index, store the record, then enforce
123
+ the size bound. Returns the records evicted to make room."""
124
+ with self._lock:
125
+ root = rec.root_run_id
126
+ seq = self._seq.get(root, 0) + 1
127
+ self._seq[root] = seq
128
+ rec.seq = seq
129
+ rec.arrival = self._next_arrival
130
+ self._next_arrival += 1
131
+ key = (root, rec.call_id, rec.attempt)
132
+ if key in self._records:
133
+ raise ValueError(f"call {rec.call_id!r} attempt {rec.attempt} is already stored")
134
+ self._records[key] = rec
135
+ ckey = (root, rec.call_id)
136
+ if rec.attempt > self._attempts.get(ckey, 0):
137
+ self._attempts[ckey] = rec.attempt
138
+ self._count_by_call[ckey] = self._count_by_call.get(ckey, 0) + 1
139
+ roots = self._roots_by_call.setdefault(rec.call_id, {})
140
+ roots.pop(root, None)
141
+ roots[root] = None # newest last
142
+ now = self.clock()
143
+ run = self._runs.get(root)
144
+ if run is None or not run.open:
145
+ # A new run, or one seen again after idle eviction (6.1): it starts
146
+ # fresh; records the old run left in a session stay reachable
147
+ # through the session only.
148
+ run = self._runs[root] = _Unit(rec.arrival)
149
+ run.records[key] = rec
150
+ run.last_activity = now
151
+ if rec.session_id is not None:
152
+ skey = (rec.agent_id, rec.session_id)
153
+ sess = self._sessions.get(skey)
154
+ if sess is None:
155
+ sess = self._sessions[skey] = _Unit()
156
+ sess.records[key] = rec
157
+ sess.last_activity = now
158
+ bkey = (root, rec.batch_id)
159
+ self._batch_first.setdefault(bkey, rec.arrival)
160
+ self._batch_count[bkey] = self._batch_count.get(bkey, 0) + 1
161
+ if self._latest_batch.get(root) != rec.batch_id:
162
+ self._latest_batch[root] = rec.batch_id
163
+ self._batch_snapshot.pop(root, None) # 4.2: only the newest batch's snapshot is kept
164
+ removed = self._enforce_size(now)
165
+ self._flush()
166
+ return removed
167
+
168
+ # ------------------------------------------------------------ durable mirror (4.1a)
169
+
170
+ def persist(self, rec: CallRecord, outcome: dict | None = None) -> None:
171
+ """Write the record (and its outcome, when given) through to the durable
172
+ store with the run's current `seq` counter. The guard calls it when a
173
+ `before_call` outcome exists; `update` and `complete` call it themselves."""
174
+ if self.durable is None:
175
+ return
176
+ try:
177
+ with self._lock:
178
+ seq = self._seq.get(rec.root_run_id)
179
+ self.durable.put(rec, outcome, seq)
180
+ except Exception as exc: # noqa: BLE001 - the memory store stays the truth for this process
181
+ self._durable_failed(exc, rec)
182
+
183
+ def persist_if_stored(self, rec: CallRecord, outcome: dict | None = None) -> bool:
184
+ """`persist`, only while `rec` is still the stored object: a record whose
185
+ unit ended while its call was in flight leaves no orphan row behind."""
186
+ with self._lock:
187
+ if self._records.get((rec.root_run_id, rec.call_id, rec.attempt)) is not rec:
188
+ return False
189
+ self.persist(rec, outcome)
190
+ return True
191
+
192
+ def durable_sweep(self, now: float) -> None:
193
+ """4.1a retention: the durable store's own sweep, with the periodic one."""
194
+ if self.durable is None:
195
+ return
196
+ try:
197
+ self.durable.sweep(now)
198
+ except Exception as exc: # noqa: BLE001
199
+ self._durable_failed(exc, None)
200
+
201
+ def _flush(self) -> None:
202
+ """Mirror the drops, run closes and run ends collected under the lock.
203
+ Called at the end of every public method that can drop a record."""
204
+ if self.durable is None:
205
+ return
206
+ with self._lock:
207
+ dropped, self._dropped = self._dropped, []
208
+ closed, self._closed = self._closed, []
209
+ ended, self._ended = self._ended, []
210
+ if not dropped and not closed and not ended:
211
+ return
212
+ try:
213
+ if dropped:
214
+ self.durable.delete(dropped)
215
+ for root in closed:
216
+ if root not in ended:
217
+ self.durable.close_run(root)
218
+ for root in ended:
219
+ self.durable.end_run(root)
220
+ except Exception as exc: # noqa: BLE001
221
+ self._durable_failed(exc, None)
222
+
223
+ def _durable_failed(self, exc: BaseException, rec: CallRecord | None) -> None:
224
+ if self.on_durable_error is not None:
225
+ try:
226
+ self.on_durable_error(exc, rec)
227
+ except Exception: # noqa: BLE001
228
+ pass
229
+
230
+ def reset_after_fork(self) -> None:
231
+ """A forked child: the lock a parent thread may have held is replaced."""
232
+ self._lock = threading.RLock()
233
+
234
+ def has_open_run(self, root_run_id: str) -> bool:
235
+ with self._lock:
236
+ run = self._runs.get(root_run_id)
237
+ return run is not None and run.open
238
+
239
+ def has_session(self, agent_id: str, session_id: str) -> bool:
240
+ with self._lock:
241
+ return (agent_id, session_id) in self._sessions
242
+
243
+ def restore(self, items: list[tuple[CallRecord, Any]], open_runs: dict[str, int]) -> list[CallRecord]:
244
+ """4.1a, load on resume: place records loaded from the durable store in
245
+ memory, in their stored order, with fresh arrival indices below anything
246
+ appended later. A root run in `open_runs` becomes an open unit with that
247
+ `seq` counter (or the highest restored `seq`, if higher); the records of
248
+ any other root run join their session only, as records of a closed run
249
+ do. A restored unit counts its idle time from the restore (4.1a: the
250
+ process was dead, not the run idle). Records already in memory are left
251
+ alone. Returns the restored records."""
252
+ restored: list[CallRecord] = []
253
+ with self._lock:
254
+ when = self.clock()
255
+ for rec, _ in items:
256
+ root = rec.root_run_id
257
+ key = (root, rec.call_id, rec.attempt)
258
+ if key in self._records:
259
+ continue
260
+ rec.arrival = self._next_arrival
261
+ self._next_arrival += 1
262
+ self._records[key] = rec
263
+ ckey = (root, rec.call_id)
264
+ if rec.attempt > self._attempts.get(ckey, 0):
265
+ self._attempts[ckey] = rec.attempt
266
+ self._count_by_call[ckey] = self._count_by_call.get(ckey, 0) + 1
267
+ roots = self._roots_by_call.setdefault(rec.call_id, {})
268
+ roots.pop(root, None)
269
+ roots[root] = None
270
+ run = self._runs.get(root)
271
+ if run is None:
272
+ run = self._runs[root] = _Unit(rec.arrival)
273
+ run.open = root in open_runs
274
+ run.records[key] = rec
275
+ run.last_activity = max(run.last_activity, when)
276
+ if rec.session_id is not None:
277
+ skey = (rec.agent_id, rec.session_id)
278
+ sess = self._sessions.get(skey)
279
+ if sess is None:
280
+ sess = self._sessions[skey] = _Unit()
281
+ sess.records[key] = rec
282
+ sess.last_activity = max(sess.last_activity, when)
283
+ bkey = (root, rec.batch_id)
284
+ self._batch_first.setdefault(bkey, rec.arrival)
285
+ self._batch_count[bkey] = self._batch_count.get(bkey, 0) + 1
286
+ self._latest_batch[root] = rec.batch_id
287
+ self._batch_snapshot.pop(root, None)
288
+ if root in open_runs:
289
+ self._seq[root] = max(self._seq.get(root, 0), open_runs[root], rec.seq)
290
+ restored.append(rec)
291
+ for root, seq in open_runs.items():
292
+ run = self._runs.get(root)
293
+ if run is not None and run.open:
294
+ self._seq[root] = max(self._seq.get(root, 0), seq)
295
+ return restored
296
+
297
+ def _replace(self, rec: CallRecord) -> None:
298
+ key = (rec.root_run_id, rec.call_id, rec.attempt)
299
+ self._records[key] = rec
300
+ run = self._runs.get(rec.root_run_id)
301
+ if run is not None and key in run.records:
302
+ run.records[key] = rec
303
+ if rec.session_id is not None:
304
+ sess = self._sessions.get((rec.agent_id, rec.session_id))
305
+ if sess is not None and key in sess.records:
306
+ sess.records[key] = rec
307
+
308
+ def update(self, rec: CallRecord) -> bool:
309
+ """Replace the stored object for (call_id, attempt). False when the
310
+ record is no longer stored (evicted while its call was in flight)."""
311
+ key = (rec.root_run_id, rec.call_id, rec.attempt)
312
+ with self._lock:
313
+ if key not in self._records:
314
+ return False
315
+ self._replace(rec)
316
+ self.persist(rec)
317
+ return True
318
+
319
+ def discard(self, rec: CallRecord) -> bool:
320
+ """Forget a record whose call was interrupted before any decision existed
321
+ (kernel.md 10): a re-fire of its id is a new call, evaluated afresh."""
322
+ with self._lock:
323
+ key = (rec.root_run_id, rec.call_id, rec.attempt)
324
+ if self._records.get(key) is not rec:
325
+ return False
326
+ self._drop_record(key)
327
+ self._flush()
328
+ return True
329
+
330
+ def complete(self, before: CallRecord, after: CallRecord) -> bool:
331
+ """Replace `before` by `after` only if `before` is still the stored
332
+ object, so concurrent duplicate completions complete a call once (15)."""
333
+ key = (before.root_run_id, before.call_id, before.attempt)
334
+ with self._lock:
335
+ if self._records.get(key) is not before:
336
+ return False
337
+ self._replace(after)
338
+ self.persist(after)
339
+ return True
340
+
341
+ # ------------------------------------------------------------ reads
342
+
343
+ def _root_for(self, call_id: str, root_run_id: str | None) -> str | None:
344
+ if root_run_id is not None:
345
+ return root_run_id
346
+ roots = self._roots_by_call.get(call_id)
347
+ return next(reversed(roots)) if roots else None
348
+
349
+ def latest(self, call_id: str, root_run_id: str | None = None) -> CallRecord | None:
350
+ """The latest attempt of a call id in a root run (the newest root run
351
+ holding it when none is given), or None when none is stored or the
352
+ latest was evicted (a re-fire is then a new attempt, kernel.md 5)."""
353
+ with self._lock:
354
+ root = self._root_for(call_id, root_run_id)
355
+ attempt = self._attempts.get((root, call_id)) if root is not None else None
356
+ return None if attempt is None else self._records.get((root, call_id, attempt))
357
+
358
+ def latest_surviving(self, call_id: str, root_run_id: str | None = None) -> CallRecord | None:
359
+ """6.2: the latest attempt still stored, falling back to an older one
360
+ when the latest was evicted."""
361
+ with self._lock:
362
+ root = self._root_for(call_id, root_run_id)
363
+ top = self._attempts.get((root, call_id)) if root is not None else None
364
+ if top is None:
365
+ return None
366
+ for attempt in range(top, 0, -1):
367
+ rec = self._records.get((root, call_id, attempt))
368
+ if rec is not None:
369
+ return rec
370
+ return None
371
+
372
+ def last_seq(self, root_run_id: str) -> int:
373
+ with self._lock:
374
+ return self._seq.get(root_run_id, 0)
375
+
376
+ def _live_run(self, root_run_id: str) -> _Unit | None:
377
+ """The open unit of a root run. A closed unit's records are reachable
378
+ only through their own session (6.1, a run seen again after idle eviction)."""
379
+ run = self._runs.get(root_run_id)
380
+ return run if run is not None and run.open else None
381
+
382
+ def _union(self, root_run_id: str, agent_id: str, session_id: str | None) -> list[CallRecord]:
383
+ run = self._live_run(root_run_id)
384
+ run_recs = list(run.records.values()) if run is not None else []
385
+ if session_id is None:
386
+ return run_recs
387
+ sess = self._sessions.get((agent_id, session_id))
388
+ if sess is None:
389
+ return run_recs
390
+ sess_recs = list(sess.records.values())
391
+ out: list[CallRecord] = []
392
+ i = j = 0
393
+ while i < len(run_recs) and j < len(sess_recs):
394
+ a, b = run_recs[i], sess_recs[j]
395
+ if a.arrival < b.arrival:
396
+ out.append(a)
397
+ i += 1
398
+ elif b.arrival < a.arrival:
399
+ out.append(b)
400
+ j += 1
401
+ else:
402
+ out.append(a)
403
+ i += 1
404
+ j += 1
405
+ out.extend(run_recs[i:])
406
+ out.extend(sess_recs[j:])
407
+ return out
408
+
409
+ def snapshot(self, rec: CallRecord, fresh: bool = False) -> list[CallRecord]:
410
+ """4.2: the union of the root run's and the (agent, session)'s records,
411
+ minus the call itself, in arrival order, batch-atomic in membership
412
+ and, for the pre phase, in state: the first sibling's snapshot of the
413
+ newest batch serves its siblings. `fresh` (the post phase) rebuilds
414
+ the same membership with the records' current state."""
415
+ root, batch = rec.root_run_id, rec.batch_id
416
+ with self._lock:
417
+ if not fresh:
418
+ cached = self._batch_snapshot.get(root)
419
+ if cached is not None and cached[0] == batch:
420
+ return cached[1]
421
+ union = self._union(root, rec.agent_id, rec.session_id)
422
+ cutoff = self._batch_first.get((root, batch), rec.arrival)
423
+ me = rec.arrival
424
+ view = [r for r in union if r.batch_id != batch and r.arrival < cutoff and r.arrival != me]
425
+ if not fresh and self._latest_batch.get(root) == batch:
426
+ self._batch_snapshot[root] = (batch, view)
427
+ return view
428
+
429
+ def run_floor(self, root_run_id: str) -> int:
430
+ """The arrival index at which the live run of this root started (6.1): a
431
+ record of the same root run that arrived earlier belongs to an idle-
432
+ evicted run and is reachable only through its session."""
433
+ with self._lock:
434
+ run = self._live_run(root_run_id)
435
+ return run.first_arrival if run is not None else self._next_arrival
436
+
437
+ def run_end_history(self, root_run_id: str, agent_id: str, session_id: str | None) -> list[CallRecord]:
438
+ """8.2: the same union without the batch cut."""
439
+ with self._lock:
440
+ return self._union(root_run_id, agent_id, session_id)
441
+
442
+ # ------------------------------------------------------------ eviction
443
+
444
+ def _protected(self, rec: CallRecord, now: float) -> bool:
445
+ """4.3: held protects until resolved; pending protects until its call
446
+ is older than run_idle_ms (its after_call is assumed lost)."""
447
+ if rec.status == "held":
448
+ return True
449
+ if rec.status == "pending":
450
+ started = rec.started_at if rec.started_at is not None else now
451
+ return (now - started) * 1000.0 <= self.run_idle_ms # idle means strictly more (6.1)
452
+ return False
453
+
454
+ def _drop_record(self, key: Key) -> CallRecord | None:
455
+ rec = self._records.pop(key, None)
456
+ if rec is None:
457
+ return None
458
+ if self.durable is not None:
459
+ self._dropped.append(key)
460
+ root = rec.root_run_id
461
+ run = self._runs.get(root)
462
+ if run is not None:
463
+ run.records.pop(key, None)
464
+ if not run.records and not run.open:
465
+ del self._runs[root]
466
+ if rec.session_id is not None:
467
+ skey = (rec.agent_id, rec.session_id)
468
+ sess = self._sessions.get(skey)
469
+ if sess is not None:
470
+ sess.records.pop(key, None)
471
+ if not sess.records:
472
+ del self._sessions[skey]
473
+ ckey = (root, rec.call_id)
474
+ left = self._count_by_call.get(ckey, 1) - 1
475
+ if left <= 0:
476
+ self._count_by_call.pop(ckey, None)
477
+ self._attempts.pop(ckey, None)
478
+ roots = self._roots_by_call.get(rec.call_id)
479
+ if roots is not None:
480
+ roots.pop(root, None)
481
+ if not roots:
482
+ del self._roots_by_call[rec.call_id]
483
+ else:
484
+ self._count_by_call[ckey] = left
485
+ bkey = (root, rec.batch_id)
486
+ left = self._batch_count.get(bkey, 1) - 1
487
+ if left <= 0:
488
+ self._batch_count.pop(bkey, None)
489
+ self._batch_first.pop(bkey, None)
490
+ if self._latest_batch.get(root) == rec.batch_id:
491
+ self._latest_batch.pop(root, None)
492
+ self._batch_snapshot.pop(root, None)
493
+ else:
494
+ self._batch_count[bkey] = left
495
+ return rec
496
+
497
+ def _release(self, unit: _Unit, now: float | None, *, session_less_only: bool) -> list[CallRecord]:
498
+ """Drop the unit's records, keeping protected ones when `now` is given
499
+ (a bound) and dropping everything when it is None (a lifecycle release)."""
500
+ removed: list[CallRecord] = []
501
+ for key, rec in list(unit.records.items()):
502
+ if session_less_only and rec.session_id is not None:
503
+ continue
504
+ if now is not None and self._protected(rec, now):
505
+ continue
506
+ dropped = self._drop_record(key)
507
+ if dropped is not None:
508
+ removed.append(dropped)
509
+ return removed
510
+
511
+ def _close_run(self, root_run_id: str, run: _Unit, *, mirror: bool = True) -> None:
512
+ """The run is over: its seq counter goes, and its unit when no record remains."""
513
+ if run.open:
514
+ run.open = False
515
+ self.evicted_runs += 1
516
+ if self.durable is not None and mirror:
517
+ self._closed.append(root_run_id)
518
+ self._seq.pop(root_run_id, None)
519
+ self._batch_snapshot.pop(root_run_id, None)
520
+ if not run.records:
521
+ self._runs.pop(root_run_id, None)
522
+
523
+ def end_run(self, root_run_id: str, *, mirror: bool = True) -> list[CallRecord]:
524
+ """8.2: release every session-less record of the run (a hold still in
525
+ flight carries on in its call's own state) and clear the run's bookkeeping.
526
+ `mirror=False` (4.1a Integrity: an untrusted root) leaves the file alone."""
527
+ with self._lock:
528
+ run = self._runs.get(root_run_id)
529
+ removed: list[CallRecord] = []
530
+ if run is not None:
531
+ for key, rec in list(run.records.items()):
532
+ if rec.session_id is None:
533
+ dropped = self._drop_record(key)
534
+ if dropped is not None:
535
+ removed.append(dropped)
536
+ self._close_run(root_run_id, run, mirror=mirror)
537
+ self._seq.pop(root_run_id, None)
538
+ for k in [k for k in self._batch_first if k[0] == root_run_id]:
539
+ self._batch_first.pop(k, None)
540
+ self._batch_count.pop(k, None)
541
+ self._batch_snapshot.pop(root_run_id, None)
542
+ self._latest_batch.pop(root_run_id, None)
543
+ if self.durable is not None and mirror:
544
+ self._ended.append(root_run_id) # 4.1a: the file is cleaned whether or not memory held the run
545
+ self._flush()
546
+ return removed
547
+
548
+ def end_session(self, agent_id: str, session_id: str) -> list[CallRecord]:
549
+ with self._lock:
550
+ sess = self._sessions.get((agent_id, session_id))
551
+ if sess is None:
552
+ return []
553
+ removed: list[CallRecord] = []
554
+ for key, rec in list(sess.records.items()):
555
+ if rec.status != "held":
556
+ dropped = self._drop_record(key)
557
+ if dropped is not None:
558
+ removed.append(dropped)
559
+ self.evicted_sessions += 1
560
+ self._flush()
561
+ return removed
562
+
563
+ def _idle_session(self, key: tuple[str, str], now: float) -> list[CallRecord]:
564
+ sess = self._sessions.get(key)
565
+ if sess is None or (now - sess.last_activity) * 1000.0 <= self.session_idle_ms:
566
+ return []
567
+ got = self._release(sess, now, session_less_only=False)
568
+ if got:
569
+ self.evicted_records_by_age += len(got)
570
+ if key not in self._sessions:
571
+ self.evicted_sessions += 1
572
+ return got
573
+
574
+ def _idle_run(self, root: str, now: float) -> list[CallRecord]:
575
+ run = self._runs.get(root)
576
+ if run is None or (now - run.last_activity) * 1000.0 <= self.run_idle_ms:
577
+ return []
578
+ got = self._release(run, now, session_less_only=True)
579
+ self.evicted_records_by_age += len(got)
580
+ if not any(r.session_id is None for r in run.records.values()):
581
+ # Nothing session-less and protected remains: the run is over. A protected
582
+ # pending record keeps it open (and its seq counter) until it completes.
583
+ self._close_run(root, run)
584
+ return got
585
+
586
+ def evict_idle(self, now: float | None = None) -> list[CallRecord]:
587
+ """4.3: evict sessions and runs idle beyond their limits, keeping only
588
+ their protected records. Returns the evicted records."""
589
+ now = self.clock() if now is None else now
590
+ removed: list[CallRecord] = []
591
+ with self._lock:
592
+ for key in list(self._sessions):
593
+ removed.extend(self._idle_session(key, now))
594
+ for root in list(self._runs):
595
+ removed.extend(self._idle_run(root, now))
596
+ self._flush()
597
+ return removed
598
+
599
+ def evict_idle_units(self, root_run_id: str, agent_id: str, session_id: str | None,
600
+ now: float | None = None) -> list[CallRecord]:
601
+ """6.1 (idle check timing): the call's own session and root run, if idle,
602
+ before the re-execution check, whatever the sweep cadence."""
603
+ now = self.clock() if now is None else now
604
+ with self._lock:
605
+ removed: list[CallRecord] = []
606
+ if session_id is not None:
607
+ removed.extend(self._idle_session((agent_id, session_id), now))
608
+ removed.extend(self._idle_run(root_run_id, now))
609
+ self._flush()
610
+ return removed
611
+
612
+ def _enforce_size(self, now: float) -> list[CallRecord]:
613
+ removed: list[CallRecord] = []
614
+ if len(self._records) <= self.max_records:
615
+ return removed
616
+ for key, sess in sorted(self._sessions.items(), key=lambda kv: kv[1].last_activity):
617
+ if len(self._records) <= self.max_records:
618
+ return removed
619
+ got = self._release(sess, now, session_less_only=False)
620
+ self.evicted_records_by_size += len(got)
621
+ removed.extend(got)
622
+ if got and key not in self._sessions:
623
+ self.evicted_sessions += 1
624
+ for run in sorted(self._runs.values(), key=lambda u: u.last_activity):
625
+ if len(self._records) <= self.max_records:
626
+ return removed
627
+ # Records with a session belong to their session unit, handled above.
628
+ got = self._release(run, now, session_less_only=True)
629
+ self.evicted_records_by_size += len(got)
630
+ removed.extend(got)
631
+ if got and not run.records and run.open:
632
+ self.evicted_runs += 1 # 4.4: evicted "to make room"; the live run keeps its seq (4.3)
633
+ if len(self._records) > self.max_records:
634
+ self.over_limit_events += 1
635
+ return removed
636
+
637
+ # ------------------------------------------------------------ report
638
+
639
+ def history_report(self) -> dict[str, int]:
640
+ """4.4: the shape the heartbeat carries verbatim."""
641
+ with self._lock:
642
+ return {
643
+ "records": len(self._records),
644
+ "runs_open": sum(1 for r in self._runs.values() if r.open and r.records),
645
+ "sessions": len(self._sessions),
646
+ "evicted_runs": self.evicted_runs,
647
+ "evicted_sessions": self.evicted_sessions,
648
+ "evicted_records_by_age": self.evicted_records_by_age,
649
+ "evicted_records_by_size": self.evicted_records_by_size,
650
+ "over_limit_events": self.over_limit_events,
651
+ }
652
+
653
+ def bookkeeping_sizes(self) -> dict[str, int]:
654
+ """Sizes of the internal maps, for tests that check they stay bounded."""
655
+ with self._lock:
656
+ return {
657
+ "runs": len(self._runs), "sessions": len(self._sessions), "seq": len(self._seq),
658
+ "batch_first": len(self._batch_first), "batch_snapshot": len(self._batch_snapshot),
659
+ "snapshot_refs": sum(len(v[1]) for v in self._batch_snapshot.values()),
660
+ "attempts": len(self._attempts),
661
+ }